Ok ese día llego y hoy les muestro una muy reducida y mejorada versión de lo que era mi anterior código.
Código Python:
Ver original#coding: utf-8
class FSM:
def __init__(self):
self.__table = {}
self.__initial_states = []
self.__final_states = []
def add_transition(self, state, symbol, new_states):
"""
state = string
symbol = string, len = 1
new_states = list
"""
if type(new_states) == str:
self.__table[state] = {symbol: [new_states]}
else:
self.__table[state] = {symbol: new_states}
def add_initial_states(self, states):
"""
state = list or str
"""
if type(states) == str:
self.__initial_states.append(states)
else:
self.__initial_states.extend(states)
def add_final_states(self, states):
"""
states = list or str
"""
if type(states) == str:
self.__final_states.append(states)
else:
self.__final_states.extend(states)
def evaluate(self, string):
"""
returns:
0 -> Match
1 -> No match
"""
states = set(self.__initial_states)
for c in string:
new_states = set()
for state in states:
try:
self.__table[state][c]
except KeyError:
pass
else:
new_states.update(set(self.__table[state][c]))
try:
self.__table[state][""]
except KeyError:
pass
else:
new_states.update(set(self.__table[state][""]))
states = new_states.copy()
return states
def print_fsm(self):
print "Table:"
print self.__table
print "\nFinal States:"
print self.__final_states
print "\nInitial_states"
print self.__initial_states
print ""
fsm = FSM()
fsm.add_initial_states("q0")
fsm.add_transition("q0", "a", "q1")
fsm.add_transition("q1", "a", "q1")
fsm.add_transition("q2", "b", "q2")
fsm.add_final_states(("q1", "q0"))
fsm.print_fsm()
print fsm.evaluate("")
print fsm.evaluate("a")
print fsm.evaluate("aa")
print fsm.evaluate("aaa")
print fsm.evaluate("aaaa")
print fsm.evaluate("aaaaa")
print fsm.evaluate("aaaaaa")
print fsm.evaluate("ba")
Faltan muchos detalles pero se los añadiré después.