【发布时间】:2014-05-20 08:53:22
【问题描述】:
我正在尝试在 python 中实现 NFA,我已经取得了一些进展,但是我被卡住了,因为我需要使用 3d 数组,并且数组的索引需要对应于当前状态和要处理的当前字符.我必须使用整数作为数组的索引,并且我正在尝试将字符串数据类型转换为 int。但是,我收到错误消息:“列表索引必须是整数,而不是 str”,任何帮助将不胜感激。这是我目前写的代码:
"""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(char)不会导致char变为 int。int(char)是一个整数;char不受影响。
标签: python finite-automata nfa