A stochastic CFG generating automaton

The following mini program is a rudimentary class for a stochastic (non deterministic) automaton. The input is a series of states (symbols) and the output for this rudimentary example is a string that follows a simple rule: it consists of an equal number of "a"'s and "b"'s.

With a bit of tender, loving care and perhaps a rudimentary parsing language, this might well be a base for creating conlang lexicons and a few more things.

Don't hold your breath. Don't write me off, either.

The code goes below.

And by the way, I tried to tinker a bit with CSS and see what I could do.


from random import choice

class Stochastic_Factory:
	def __init__(self):
		self.token_list=[]
		self.production_dict={}
	def check_token(self,token_id):
		return (token_id in self.token_list)
	def add_token(self,token_id):
		if not self.check_token(token_id): 
			self.token_list.append(token_id)
			self.production_dict[token_id]=[]
			return token_id
		else: return None
	def is_token_final(self,token_id):
		return (len(self.production_dict[token_id])==0)
	def add_production(self,token_id,production):
		if self.check_token(token_id):
			self.production_dict[token_id].append(production)
			return token_id
		else: return None
	def yield_production(self,init_token_id='$START'):
		stack2=[init_token_id]
		stack1=[]
		while len(stack2)>0:
			q=stack2.pop()
			if self.is_token_final(q):
				stack1.append(q)
			else:
				qprod=choice(self.production_dict[q])
				if type(qprod)==tuple or type(qprod)==list:
					for i in qprod:stack2.append(i)
				else: stack2.append(qprod)
		return stack1[::-1]
			
		
	

def main(args):
	test=Stochastic_Factory()
	test.add_token('$START')
	test.add_token('a')
	test.add_token('b')
	test.add_production('$START',('a','$START','b'))
	test.add_production('$START',('a','b'))
	for i in range(10):
		print(''.join(test.yield_production('$START')))

if __name__ == '__main__':
	import sys
	sys.exit(main(sys.argv))