Reputation: 41
I am trying to implement an NFA in python and I have made some progress however I am stuck because I need to use a 3d array and the indices of the array need to correspond to the current state and the current character to be processed. I have to to use integers as indices of the array and I am trying to convert from string data type to int for this. However, I am getting the error: "list indices must be integers, not str" , any help will be much appreciated. Here is the code I've written so far:
"""Initialize States"""
q0=0
q1=1
q2=2
i=0
finstate=q2 #final state is q2
array=[[[0],[0,1]],[[2],[2]],[[],[]]] #3d array for state transitions
def accepts(state, word):
global i
if i==len(word):
return state==finstate #if last state is final state accept
char=word[i]
i+=1
int(char) #covert char to int
nextstates=array[state][char]
for i in range(len(word)):
if accepts(nextstates, word): #recursion
return True
return False
def main():
string= "01" #sample input
if accepts(q0, string):
print("accepts")
else:
print("rejects")
main()
Upvotes: 2
Views: 6000
Reputation: 1677
Well assuming the remaining of your code is correct, you should have something like
char = word[i]
i += 1
intval = int(char)
nextstates=array[state][intval]
Upvotes: 1