1
\$\begingroup\$

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
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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

answered Feb 9, 2020 at 11:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.