How are finite automata implemented in code?

前端 未结 5 1462
我在风中等你
我在风中等你 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:23

    I have implemented dfa which works for any of the dfa. But this is not in object oriented pattern.

    states=list(map(int,input("Enter States : ").split(" ")))
    symbols=list(input("Enter Symbols : ").split(" "))
    initial_state=int(input("Enter initial state : "))
    final_states=list(map(int,input("Enter final states : ").split(" ")))
    
    transitions=[]
    inlists=[]
    
    for i in range(len(symbols)):
        print("Enter transitions for symbol "+symbols[i]+" from all states :")
        for j in range(len(states)):
            inlists.append(int(input()))
        transitions.append(inlists)
        inlists=[]
    cur_state=initial_state
    
    while(1):
        cur_state=initial_state
        string=input("Enter string : ")
    
        if string=='#':
            break
    
        for symbol in string:
            print("["+str(cur_state)+"]"+"-"+symbol+"->",end="")
            cur_state=transitions[symbols.index(symbol)][cur_state]
    
        if cur_state in final_states:
            print("["+str(cur_state)+"]")
            print("String is accepted.")
        else:
            print("["+str(cur_state)+"]")
            print("String is not accepted.")
    

提交回复
热议问题