python中的简单L系统



你好,我正在寻找一种方法来实现一个简单的L系统到python中的函数中,这将需要三个参数:公理,规则和交互次数(如果迭代= 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    

如果iterations == 0,则需要返回给定的axioms。在这个函数中,你返回你得到的参数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'

相关内容

  • 没有找到相关文章

最新更新