r/learnpython • u/Confident-Acadia4217 • 13h ago
pythagoras tree
I made code for one "branch" of the Pythagoras tree, and I have no idea how to make the full tree. Can someone help? My code:
from turtle import*
x=100
while True:
for i in range (4):
fd(x)
rt(90)
rt(90)
fd(x)
lt(45)
xNaDwa= x*x/2
y= xNaDwa**0.5
x=y1
u/Sufficient-Tale6131
9h ago
•
Recursion is the way, and since you already draw the square with rt(90) the turns work out pretty neatly. Roughly: def tree(size, depth). If depth is 0 just return. Otherwise draw the square like you do now, then fd(size) so you're at the top-left corner. lt(45) and call tree(size * 0.7071, depth - 1), that's the left branch. Then rt(90) and fd(size * 0.7071), which puts you at the tip of the triangle already facing the right way, and call tree again for the right branch. After that undo the moves in reverse: bk(size * 0.7071), lt(45), bk(size).
The important part is that every call leaves the turtle exactly where and how it found it, otherwise the branches drift. Start with lt(90) so it grows upward, and put tracer(0) at the start and update() at the end, depth 8 or so is painfully slow to watch otherwise.
1
u/Free-Good9203 8h ago
the trick with `turtle` recursion is saving `pos = t.pos()` and `ang = t.heading()` right after drawing a square, then restoring them with `t.penup(); t.goto(pos); t.setheading(ang); t.pendown()` before starting the second branch. scale each child side by `size / (2 ** 0.5)` and stop once `depth == 0` so it terminates cleanly.
2
u/DHTechdev 12h ago •
A full tree needs recursion instead of a while True loop. Write a function that takes a size and a depth, draws one square, then calls itself twice for the two smaller squares on top, each with side size divided by 1.414, one turned left 45 degrees and one turned right. Stop when depth hits 0. After each branch, send the turtle back to where it started so the second branch begins in the right spot.