Object Oriented State Machine Implementation in Python


  • 0
    G

    The State class is simple:

    class State(object):
    def __init__(self, name):
        self.name = name
        self.tx = []
    def add_tx(self, char, state):
        self.tx.append((char, state))
    def trans(self, char):
        for t in self.tx:
            c, s = t
            if char in c:
                return s
        return None
    

    But the main function is not

    class Solution:
    def isNumber(self, s):
        echar = '\x5b'
        # see http://oi61.tinypic.com/2ex0e83.jpg
        # create states
        start = State('start')
        num1 = State('number 1')
        point1 = State('null point?')
        point2 = State('num point')
        num2 = State('number 2')
        e = State('e')
        signe = State('sign e')
        num3 = State('number 3')
        end = State('end')
        # define trans
        start.add_tx(['+', '-'], start)
        start.add_tx(['.'], point1)
        start.add_tx(string.digits, num1)
        point1.add_tx(string.digits, num2)
        num1.add_tx(string.digits, num1)
        num1.add_tx(['.'], point2)
        num1.add_tx(['e'], e)
        num1.add_tx([echar], end)
        point2.add_tx(string.digits, num2)
        point2.add_tx(['e'], e)
        point2.add_tx(echar, end)
        num2.add_tx(string.digits, num2)
        num2.add_tx(['e'], e)
        num2.add_tx(echar, end)
        e.add_tx(['+', '-'], signe)
        e.add_tx(string.digits, num3)
        signe.add_tx(string.digits, num3)
        num3.add_tx(string.digits, num3)
        num3.add_tx(echar, end)
        # strip input string
        s = s.strip() + echar
        # state ransfer
        cur = start
        for c in s:
            cur = cur.trans(c)
            if cur is None:
                return False
        if cur is not end:
            return False
        return True

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.