1
我想在python中實現一個NFA,但我已經取得了一些進展,但因爲我需要使用一個3d數組,並且數組的索引需要對應於當前狀態,當前要處理的字符。我不得不使用整數作爲數組的索引,我試圖從字符串數據類型轉換爲int爲此。但是,我收到錯誤:「列表索引必須是整數,而不是str」,任何幫助將不勝感激。這裏是我到目前爲止已經編寫的代碼:在Python中實現NFA
"""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()
'INT(焦炭)'不會導致焦炭' '成爲一個整數。 'int(char)'是一個int; 'char'不受影響。 – user2357112