INTRODUCTION |
Maybe you remember the slightly uncanny story of the man with the hollow tooth from your early childhood:
|
|
RECURSIVE STAIRCASE |
In a minute, you will instruct the turtle to draw a single step by defining the function step(). Then, you can simply call stairs(3) in order to build a stair with three steps. But wait, there is not yet an indication that nothing should happen when you build a staircase with 0 steps. You can easily solve this by using an if condition: if n == 0: return With the statement return, you tell the turtle to quit and return to its previous work. Your program should now look like this: from gturtle import * def stairs(n): if n == 0: return step() stairs(n - 1) def step(): forward(50) right(90) forward(50) left(90) makeTurtle() fillToHorizontal(0) stairs(3) Highlight program code
|
MEMO |
Recursion is a fundamental solution method in the fields of mathematics and computer science, in which a problem is solved by turning it into the same but slightly simplified problem. Thus, if f is a function that solves the problem, in a (direct) recursion, f is used again in the definition of f [more... In a indirect recursion other functions that contain f used in the definition of f instead of f itself]. At first glance it may seem strange that someone would want to solve a problem in a way that already presupposes the solution. However, then we overlook an essential point: it is not the same problem that we use to find the solution, but one that is closer to the solution. In order to do this, we mostly use an integer parameter n, which we pass to f def f(n):
...
def f(n):
...
f(n-1)
...
def f(n): if n == 0: return ... f(n - 1) ... |
THE PYTHAGORAS TREE |
It is well-known that the implementation of a recursive program is unusual. Thus, the following will give you a detailed guide on how to proceed.
from gturtle import * import math def tree(s): if s < 2: return square(s) forward(s) s1 = s / math.sqrt(2) left(45) tree(s1) right(90) forward(s1) tree(s1) back(s1) left(45) back(s) def square(s): repeat 4: forward(s) right(90) makeTurtle() ht() setPos(-50, -200) tree(100) Highlight program code
|
MEMO |
It is very important that the turtle returns back to its initial location with the initial viewing direction in many recursively defined figures. |
EXERCISES |
|