python中的简单L系统

时间:2018-01-05 12:27:51

标签: python python-3.x function iteration l-systems

你好我正在寻找一种方法在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    

1 个答案:

答案 0 :(得分:1)

如果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'