Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中{ab,abc}*的非确定性有限自动机_Python_Python 3.x_Dfa_Nfa - Fatal编程技术网

Python中{ab,abc}*的非确定性有限自动机

Python中{ab,abc}*的非确定性有限自动机,python,python-3.x,dfa,nfa,Python,Python 3.x,Dfa,Nfa,我一直在尝试画这个非确定性有限自动机: NFA语言{ab,abc}*的州数不超过3个,我得出了下图中的解决方案: 问题似乎在于代码逻辑,因为我的代码总是打印“拒绝”。如果有人能给出一些关于如何编写此算法的提示,我将不胜感激 print("Insert below the string: ") string = str(input()) def state_q0(string): if len(string) == 0: print("s

我一直在尝试画这个非确定性有限自动机:

NFA语言{ab,abc}*的州数不超过3个,我得出了下图中的解决方案:

问题似乎在于代码逻辑,因为我的代码总是打印“拒绝”。如果有人能给出一些关于如何编写此算法的提示,我将不胜感激

print("Insert below the string: ")
string = str(input())


def state_q0(string):
    if len(string) == 0:
        print("string not accepted")
    else:
        if string[0] == "a":
            state_q1(string[1:])
        elif string[0] == "b":
            print("rejected")


def state_q1(string):
    if len(string) == 0:
        print("string not accepted")
    else:
        if string[1] == "b":
            state_q2(string[2:])
        else:
            print("rejected")


def state_q2(string):
    if len(string) == 0:
        print("string not accepted")
    else:
        if string[2] == "c":
            print("accepted -> q0")
        elif string[2] == "b":
            print("rejected")


state_q0(string)


您应该始终查看字符串的第一个字符,并使用除第一个字符以外的所有内容调用递归调用

在您的图表中也没有注意到,但是我假设
q0
是接受状态,因为它对应于
(ab+abc)*

因此,以您的风格(我个人不会使用,但可以):

然而,我将如何对NFA进行编码:

转换=[
{“a”:{1},
{“b”:{0,2},
{“c”:{0}
]
启动状态=0
接受_状态={0}
def nfa(w):
cur_states={starting_state}
对于w中的c:
如果不是当前状态:返回“拒绝”
cur_states=set.union(*
(转换[s].get(c,set())表示当前状态下的s)
如果当前状态为“接受”,则返回“接受”,否则返回“拒绝”

您是否可以添加一个示例,说明在给定特定输入的情况下,您希望输出的内容?谢谢您的解释。我将花一些时间研究代码和实现,然后回来。
def q0(s):
    if not s: return "accept"  # Accepting state.
    if s[0] == "a": return q1(s[1:])
    return "reject"

def q1(s):
    if not s: return "reject"
    # NFA, must try both edges.
    if (s[0] == "b" and q0(s[1:]) == "accept" or
        s[0] == "b" and q2(s[1:]) == "accept"):
        return "accept"
    return "reject"

def q2(s):
    if not s: return "reject"
    if s[0] == "c": return q0(s[1:])
    return "reject"