\$\begingroup\$
\$\endgroup\$
I have created a fractal tree based on a Lindenmayer System in Python. If you could tell me about any algorithmic or efficiency-based problems in the code, I would be grateful.
import turtle
import time
t = turtle.Pen()
branch = []
code = "1[0]0" # Change this to modify the structure of the tree
t.left(90)
t.up()
t.backward(300)
t.down()
t.speed(10)
for c in code:
if c == "1":
t.pencolor("brown")
t.forward(100) # Change this to modify the size of the tree
elif c == "0":
t.pencolor("green")
t.forward(3) # Change this to modify the size of the leaves
elif c == "[":
t.left(45)
branch.append((t.position(), t.heading()))
elif c == "]":
t.up()
t.goto(branch[len(branch) -1][0], None)
t.setheading(branch[len(branch) -1][1])
t.right(90)
t.down()
del branch[len(branch) -1]
greybeard
7,4313 gold badges21 silver badges55 bronze badges
asked Feb 9, 2020 at 10:44
1 Answer 1
\$\begingroup\$
\$\endgroup\$
Personally I don't like multiples if statements inside a for, here is my suggestion:
def handler_option_c(t, b):
t.pencolor("brown")
t.forward(100) # Change this to modify the size of the tree
handlers = { "c" : handler_option_c, ....
And you do the same for the other options, and then on your main
for c in code:
handlers[c](t, branch)
Or you can put that on a lambda also
lang-py