这是我的项目,它是绘图机器人:
我设法做 F 和 R 功能。但是我的 L 函数总是出现故障。这是我的代码:
def func(list1):
numOfElements = int(len(list1))
for i in range(numOfElements):
if list1[i] == "L":
list2 = list1.copy()
for j in range(i):
list2.pop(j)
list2.pop(0)
while(list1[i]!="]"):
func(list2)
i=i+1
if list1[i] == "F":
value = list1[i + 1]
tim.forward(value)
if list1[i] == "R":
value = list1[i + 1]
tim.right(value)
else:
pass
我正在使用此图像中的示例。我的代码将它们分成tokens。然后我把它们放在名单上。 [![在此处输入图像描述][2]][2]
如果我有一个 L 函数,我可以做到这一点,但如果有嵌套的 L 函数,我就无法解决。如何用我的 L 函数解决这个问题?
回答1
在这种情况下,您不希望 for i in range(...)
循环在循环内递增,i=i+1
不会影响下一次迭代中 i
的 value。与 C 不同,Python for
循环在下一次迭代中忽略对迭代变量的更改。
此外,不需要复制 tokens 。我们只需要正确跟踪我们在 tokens 列表中的位置。这包括有一个递归调用返回它在 tokens 列表中的距离,然后它到达 ']'
并返回。
让我们把所有这些放在一起并使用有意义的变量名:
from turtle import Screen, Turtle
example = ['L', 36, '[', 'L', 4, '[', 'F', 100, 'R', 90, ']', 'R', 10, ']']
def func(tokens, index=0):
while index < len(tokens):
command = tokens[index]
index += 1
if command == 'L':
repetitions = tokens[index]
index += 2 # also move past '['
for _ in range(repetitions):
new_index = func(tokens, index)
index = new_index
elif command == 'F':
distance = tokens[index]
index += 1
turtle.forward(distance)
elif command == 'R':
angle = tokens[index]
index += 1
turtle.right(angle)
elif command == ']':
break
return index
screen = Screen()
turtle = Turtle()
func(example)
screen.exitonclick()