Controlling depth of recursion in python function

735 views Asked by At

I have the following code:

from turtle import *
speed(0)

def polygon(xangle, steps):
    n = 360 // xangle # number of sides required for chosen exterior angle
    for i in range(n): 
        forward(steps)
        right(xangle)

def corner_polygons(xangle, steps):
    n = 360 // xangle
    for i in range(n):
        draw_polygon(xangle, steps//5) # draw smaller polygon
        forward(steps)
        right(xangle)

def double_corner_polygons(xangle, steps):
    n = 360 // xangle
    for i in range(n):
        corner_polygons(xangle, steps//5)
        forward(steps)
        right(xangle)

The first function draws a polygon with the specified exterior angle (xangle) and side lengths equal to steps. The second function draws the same polygon as before, but now puts a smaller polygon in each of the corners. The third function goes one level deeper, for example:

double_corner_polygons(60, 150)

gives :

enter image description here

I want to add another parameter, recursions that controls how deep the drawing goes, so that I don't have to write new functions each time. I can't seem to get it quite right. My attempt so far:

def corner_polygons_recursive(xangle, steps, recs):
    n = 360 // xangle
    for i in range(n):
        for j in range(1, recs+1):
            corner_polygons(xangle, steps//5*j) 
        forward(steps)
        right(xangle)
1

There are 1 answers

0
cdlane On BEST ANSWER

It may be simpler than you're trying to make it, perhaps something like:

import turtle

def corner_polygons_recursive(angle, side, depth):

    if depth < 1:
        return

    n = 360 // angle

    for _ in range(n):
        corner_polygons_recursive(angle, side / 3, depth - 1)
        turtle.forward(side)
        turtle.right(angle)

corner_polygons_recursive(60, 150, 4)

turtle.exitonclick()

OUTPUT

enter image description here