pythonpython-3.xfunctioniterationl-systems

Simple L -system in python


Hello I'm looking for a way to implement a simple L-system into function in python which would take three arguments : axiom , rules and number of interations(if iterations = 0 output would be previously input axiom). I came up with some code it only works on 1 iteration and I dont know how to implement more.

The code I came up with :

#  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    

Solution

  • You need to return the given axioms if iterations == 0. In this function, you return the argument axioms you've been given, so that if iterations == 0, you will return the given, untouched axioms.

    Then, later on, at the end of your iteration, if iteration there is, the newly created axioms you get from the iteration is transfered into axioms so that you will return the good value, and if need be, the next iteration will have the newly created axioms to iterate on. :)

    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'