Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to implement nfa in python

#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()
Comment

PREVIOUS NEXT
Code Example
Python :: python how to close the turtle tab on click 
Python :: convert ui to py 
Python :: sklearn model persistence 
Python :: python import shelve 
Python :: struct trong Python 
Python :: Local to ISO 8601 without microsecond: 
Python :: how to run function when file is modified python 
Python :: for_else_and_while_else_statement 
Python :: generate jwt token just passing userid in rest_framework_simplejwt 
Python :: AI code for diagnosing diseases 
Python :: create new model description odoo 
Python :: .format() multiple placeholders 
Python :: install requests-html modlule click on the link to learn more about requests-html 
Python :: Doubleclick .py Prep Mac 
Python :: perfect power function python 
Python :: give the factorials of 6 in python 
Python :: Python getting content from xl range 
Python :: Example pandas.read_hdf5() 
Python :: add Elements to Python list Using extend() method 
Python :: pandas check if string has only spaces 
Python :: python gender input 
Python :: lambda2 criterion python 
Python :: How to use glob.escape() function in python 
Python :: list expression inside bracket python 
Python :: no definition 
Python :: Python NumPy asarray Function Example Tuple to an array 
Python :: advanced python code copy and paste 
Python :: (ax=self.canv.axes ,style="ro--") 
Python :: NumPy trim_zeros Syntax 
Python :: NumPy bitwise_xor Code When inputs are numbers 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =