您好,我正在寻找一种在python中将简单的L系统实现为函数的方法,该方法需要三个参数:公理,规则和交互次数(如果迭代次数= 0,则以前输入的是公理)。我想出了一些代码,它仅适用于1次迭代,而且我不知道如何实现更多代码。
我想出的代码:
# x = axiom
# y = rules
# z would be iterations which I dont know how to implement
def lsystem(x,y):
output = ''
for i in x:
if i in y:
output += y[i]
else:
output += i
print(output)
rules = { "A" : "ABA" , "B" : "BBB"}
# output lsystem("AB",rules) ---> ABABBB
最佳答案
如果axioms
,则需要返回给定的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'
关于python - python中的简单L系统,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48113662/