How are finite automata implemented in code?

前端 未结 5 1488
我在风中等你
我在风中等你 2020-12-14 01:59

How does one implement a dfa or an nfa for that matter in Python code?

What are some good ways to do it in python? And are they ever used

5条回答
  •  甜味超标
    2020-12-14 02:18

    Here I present a recursive solution for NFA. Consider the following nfa:

    The transitions can be represented using list of lists as follows:

    transition = [[[0,1],[0]], [[4],[2]], [[4],[3]], [[4],[4]],[[4],[4]]]
    

    Note: State 4 is a hypothetical state. Once you go to that state, you can't move further. It is helpful when you can't read the input from the current state. You directly go to the state 4 and say input is not accepted for current progress(Check other possibilities by going back). e.g, if you are at q1, and the current input symbol is 'a', you go to state 4 and stop computing further.

    Here is the Python code:

    #nfa simulation for (a|b)*abb
    #state 4 is a trap state
    
    
    import sys
    
    def main():
        transition = [[[0,1],[0]], [[4],[2]], [[4],[3]], [[4],[4]]]
        input = raw_input("enter the string: ")
        input = list(input) #copy the input in list because python strings are immutable and thus can't be changed directly
        for index in range(len(input)): #parse the string of a,b in 0,1 for simplicity
            if input[index]=='a':
                input[index]='0' 
            else:
                input[index]='1'
    
        final = "3" #set of final states = {3}
        start = 0
        i=0  #counter to remember the number of symbols read
    
        trans(transition, input, final, start, i)
        print "rejected"
    
    
    
    def trans(transition, input, final, state, i):
        for j in range (len(input)):
            for each in transition[state][int(input[j])]: #check for each possibility
                if each < 4:                              #move further only if you are at non-hypothetical state
                    state = each
                    if j == len(input)-1 and (str(state) in final): #last symbol is read and current state lies in the set of final states
                        print "accepted"
                        sys.exit()
                    trans(transition, input[i+1:], final, state, i) #input string for next transition is input[i+1:]
            i = i+1 #increment the counter
    
    
    main()
    

    Sample Run(strings ending with abb are accepted):

    enter the string: abb
    accepted
    
    enter the string: aaaabbbb
    rejected
    

提交回复
热议问题