""" CS101 Class examples - Recursion """ import turtle as t def drawCurve(L, level): """ Recursively draws an inward turning curve """ if level > 0: t.forward(L) t.left(30) drawCurve(L*.95, level-1) t.right(30) t.backward(L) def drawCurveScene(L, level): """ Moves the turtle to the left of the screen, draws a curve """ # pick up the pen and move the turtle so it starts to the left t.penup() t.goto(-t.window_width()/4 + 20, 0) t.pendown() drawCurve(L, level) t.done() # goBack illustrates pending operations after the recursive call def goBack(n): """ Prints "Go" for each recursive call; "Stop" at base case; then prints "Back" on the way out of the recursion. """ if n == 0: print("Stop") else: print("Go", n) goBack(n-1) print("Back", n) # What output does this call produce? # goBack(3) def mystery(s): """ Recursive function that takes a string as input and returns... """ if len(s) == 1: return int(s) else: return int(s[0]) + mystery(s[1:]) # What output does this call produce? # mystery('1337') def drawTree(length, gen): """ Draws recursive tree with initial trunk length and number of branches given by parameters. Ends drawing at same position where drawing started. """ if gen > 0: t.forward(length) # draw tree branch t.right(45) drawTree(length/2, gen-1) # draw right subtree t.left(45*2) # undo right turn, then turn left again drawTree(length/2, gen-1) # draw left subtree t.right(45) # undo left turn t.backward(length) # trace back down the tree branch def drawTreeScene(): """ Moves the turtle to the bottom of the screen, points it upward, and draws a tree. """ # turn off drawing animation (too slow otherwise) # t.tracer(False) # pick up the pen and move the turtle so it starts at the left edge of the canvas t.penup() t.goto(0, -t.window_height()/2 + 20) t.left(90) t.pendown() # draw the tree by calling your function drawTree(200,4) # finished # t.update() t.done()