在Python中实现NFA

2 投票
1 回答
5710 浏览
提问于 2025-04-18 07:04

我正在尝试用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()

1 个回答

1

好的,假设你其他的代码都是正确的,你应该有类似下面的东西:

char = word[i]
i += 1
intval = int(char)
nextstates=array[state][intval]

撰写回答