您需要返回给定的axioms
if iterations == 0
。在这个函数中,您返回axioms
给定的参数,因此如果iterations == 0
,您将返回给定的、未触及的公理。
然后,稍后,在您的末尾iteration
,如果iteration
有,则将从中获得的新创建的公理iteration
转移到axioms
,以便您返回良好的值,如果需要,下一个iteration
将有新创建的公理进行迭代在。:)
def lsystem(axioms, rules, iterations):
# We iterate through our method required numbers of time.
for _ in range(iterations):
# Our newly created axioms from this iteration.
newAxioms = ''
# This is your code, but with renamed variables, for clearer code.
for axiom in axioms:
if axiom in rules:
newAxioms += rules[axiom]
else:
newAxioms += axiom
# You will need to iterate through your newAxioms next time, so...
# We transfer newAxioms, to axioms that is being iterated on, in the for loop.
axioms = newAxioms
return axioms
rules = { "A" : "ABA" , "B" : "BBB"}
print(lsystem('AB', rules, 0))
# outputs : 'AB'
print(lsystem('AB', rules, 1))
# outputs : 'ABABBB'
print(lsystem('AB', rules, 2))
# outputs : 'ABABBBABABBBBBBBBB'