2

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    
Piotrek Wcisło
  • 85
  • 1
  • 10
  • What is the problem of your code ? You only wish to know how to implement the `z` parameter ? How would it need to be implemented : If z is 0, if z is superior to the number of iteration in x, etc... – IMCoins Jan 05 '18 at 12:42
  • Yes I want want to know how to implement z parameter, I think it should be implemented as some kind of loop. And the steps for z =2 would look like this output =AB - - - > output =ABABBB - - - - > output ABABBBABABBBBBBBBB – Piotrek Wcisło Jan 05 '18 at 13:15
  • Keep me up to date if my answer fits your needs. ;) – IMCoins Jan 05 '18 at 13:41
  • Works as intended . Thank you very much – Piotrek Wcisło Jan 05 '18 at 15:33

1 Answers1

3

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'
IMCoins
  • 3,149
  • 1
  • 10
  • 25
  • I don't think this code is correct. If we set the rules as : Rules : (A->A+B, B->A-B) The Result at N=3 should be : A+B+A-B+A+B-A+B But the answer here is : A+B+A-B+A+B-A-B – Chaitanya Kumar Apr 13 '20 at 16:58