Python Recursive Squares

Viewed 293

I want to generate a recursive pattern

However, I'm very clueless what do about the fracctal function and how to write that function to get my desired output.

code -

from turtle import Turtle, Screen
import math

t = Turtle()
s = Screen()
t.speed(0)

def square(x, y, side):
    t.setpos(x,y)
    for i in range(4):
        t.forward(side)
        t.right(90)

def tiltsquare(x, y, side):
    t.left(45)
    square(x, y, side)

def squareinsquare(x, y, side):
    square(x, y, side)
    half = side / 2
    b = math.sqrt(half**2 + half**2)

    tiltsquare(x, y - side/2, b)

squareinsquare(0, 0, 200)

s.exitonclick()
2 Answers

The recurring pattern is as follows:

  1. Draw a square from the current point
  2. Move half-way the first edge and then turn 45°: this is where the next smaller square will start
  3. Divide the current size by √2, this will be the size of the next square so it gets inscribed in the current square.
  4. Repeat from the top

So, I would remove the x and y parameters for your square function: it should just start using the current position and direction.

def square(side):
    for i in range(4):
        t.forward(side)
        t.right(90)

def fractal(x, y, stSide, k):  
    t.setpos(x, y)
    for i in range(k):
        square(stSide)
        t.forward(stSide / 2)
        t.right(45)
        stSide /= math.sqrt(2) 

fractal(0, 0, 200, 10)

If you should not change the original square function, then just read the turtle's position and pass that as argument to square, which will then do a needless call to setpos():

def square(x, y, side):
    t.setpos(x, y)
    for i in range(4):
        t.forward(side)
        t.right(90)

def fractal(x, y, stSide, k):  
    t.setpos(x, y)
    for i in range(k):
        square(*t.pos(), stSide)
        t.forward(stSide / 2)
        t.right(45)
        stSide /= math.sqrt(2) 

fractal(0, 0, 200, 5)

I don't know about fractals but this can be achieved with a recursive function that draws a square then moves half way through one side, rotates 45% and recurses with a size that is half the diagonal of the square just drawn.

import turtle as tg

def squares(n,side=200):
    if not n: return           # nesting done, end recursion
    for _ in range(4):         # draw square
        tg.forward(side)
        tg.left(90)
    tg.forward(side/2)         # move half way through side
    tg.left(45)                # turn 45% 
    squares(n-1,side*2**0.5/2) # recurse with half diagonal: side * √2 / 2

squares(10)

You could also have it draw from the inside out by reversing the intermediate movements and rotations:

def squares(n,side=10):
    if not n: return           # nesting done, end recursion
    tg.right(45)               # turn 45%
    tg.backward(side/2)        # move back to starting corner
    for _ in range(4):         # draw square
        tg.forward(side)
        tg.left(90)
    squares(n-1,side*2**0.5)   # recurse with larger size
Related