2

您好,我正在寻找一种在 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    
4

1 回答 1

3

您需要返回给定的axiomsif 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'
于 2018-01-05T13:20:18.423 回答