Explanation for the code is code comments:
class LSystem():
#init the word,productions,generations
def __init__(self,w,p,g):
self.word = w
self.productions = p
self.generations = g
def rewrite(self):
#get word into a local variable
a = self.word
#if generations=0, output word
if self.generations==0:
print(self.word)
return
else:
#run loop until generations is > 0
while self.generations>0 :
#ans stored language generated at each genearation
ans = ""
#run loop for the length of current word
for i in range(len(a)):
#if there is a production for current alphabet then expand and
append it to ans
if a[i] in self.productions:
ans+=self.productions[a[i]]
#else just let the alphabet remain the same as stated in the
question
else:
ans+=a[i]
#update word to current expanded language
a = ans
#decrement generations
self.generations-=1
print(a)
#driver code
sys = LSystem('A',{'A':'AB','B':'A'},4)
print("For generations : 4")
sys.rewrite()
ktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre r complexpy X gramarExpansion.p x Natrie. Type . Size 1 class LSysten() init the word,productions,generations def-Anit-(self,พ.อ.g): self.word - w seLf.productions p self.generations def rewrite(self) #get bord into local variable a-lf.word if generations-o, output word if self.generations=弌: print(self-word) 10 12 13 Vaniab e explorer Fle xp orer Hal 14 return Fython corsle 16 #run 1.nop until generations í > e while self.generations> fans stored Language generated at each genearation Canale 1Ax 17 19 run Loop for the Length of current word for i in range(len(a)) #if there i production A r current alphabet then expand end append it to if i] in self.productions: ans+ self.productions[ali1l delse just Eet the alphahet remain the sane as stated in the question else: In [44] runfileC:/Users/Rogue/Desktop/eranarExpansion.py, wdir- 'C: Users/ Rague/Desktap) For generations : 0 21 24 In [45]: runfile('C:/Users/Rogue/Desktop/granarExpansion.py', wdir-'C:/Users/ Rogue/Desktop) Far generations 2 2/ #update word to current expanded language adecrement generations self.generations--1 坩 In 146]: rufile( C:/Users/Rogue /Desktop/granarExpansion-py', wdir-C:/Users/ Rogue/Desktop) For Eenerations :4 31 print(a) 33#driver code 32 5 print( or generations : 4 36 sys.rewrite) In [471 runfileC:/Users/Rogue/Desktop/eranarExpansion.py, wdir- 'C: Users/ Rague/Desktap) For generations : 4 In (48 Hstcry log Python console Permissiars KW End-af-lines: CRLF Encading: UIF- Line 22 Column:48 Memory 61% :11 AM O Typc here to searc ENG 5/29/2019
In [44]: runfile('C:/Users/Rogue/Desktop/gramarExpansion.py, wdir-'C:/Users Rogue/Desktop) For generations0 In [45]: runfile('C:/Users/Rogue/Desktop/gramarExpansion.py', wdir-'C:/Users/ Rogue/Desktop') For generations 2 In [46]: runfile('C:/Users/Rogue/Desktop/gramarExpansion.py', wdir-'C:/Users/ Rogue/Desktop') For generations:4 ABAABABA