尝试实施 DFA 但代码生成错误

Trying to implement DFA but the code is generating errors

代码:-

#Shortest DFA implementation in Python
S,D,F=input()
s=1
for c in S:s=D[s,c]
print(["Not a chance!","Accepted!"][F&s>0])

输入:- 输入是字符串 S、增量函数 D 和最终状态掩码 F 的三元组。我用 2 的幂对每个状态进行编号,因此 F 只是每个接受状态的或。 D 是来自 (state,input char) -> state.

的映射

示例输入(接受所有以 b 结尾的字符串):

'abab',{(1,'a'):1,(1,'b'):2,(2,'a'):1,(2,'b'):2},2

输出:-

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-506f09a31940> in <module>()
      1 #Shortest DFA implementation in Python
----> 2 S,D,F=input()
      3 s=1
      4 for c in S:s=D[s,c]
      5 print(["Not a chance!","Accepted!"][F&s>0])

ValueError: too many values to unpack (expected 3)

同样,下面的代码是实现一个NFA。但它会抛出另一种错误,即使在添加 eval() 之后也是如此。代码如下:-

#Shortest NFA implementation
S,D,F=eval(input())
s=1
for c in S:
 t,s=s,0
 for a,b in D[c]:s|=t/a%2*b
print(["Not a chance!","Accepted!"][F&s>0])

输入:- 我们像以前一样将状态编号为 2 的幂。 D 是从输入字符到由该字符标记的转换列表的映射。

示例输入(接受所有以 b 结尾的字符串):

'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2

得到的输出为:-

'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-7e5418d2d6fc> in <module>()
      4 for c in S:
      5  t,s=s,0
----> 6  for a,b in D[c]:s|=t/a%2*b
      7 print(["Not a chance!","Accepted!"][F&s>0])

TypeError: unsupported operand type(s) for |=: 'int' and 'float'

请告诉我在上述代码中需要进行哪些必要但最少的修改才能成功执行并产生所需的输出。

此代码在 Python 2 中有效,但在 Python 3 中无效。我怀疑当您使用 Python 3 时,该代码实际上是为 Python 2 设计的. input in Python 2 not only reads in a string from the input, but it also performs an eval statement which means that it will take the string and convert it into Python syntax. input in Python 3 returns 是你输入的字符串。eval 不再像你在 Python 中看到的那样执行 2. 模仿什么你在 Python 2 中看到,你需要 运行 evalinput 之上:

In [1]: S,D,F = eval(input())
'abab',{(1,'a'):1,(1,'b'):2,(2,'a'):1,(2,'b'):2},2

In [2]: S
Out[2]: 'abab'

In [3]: D
Out[3]: {(1, 'a'): 1, (1, 'b'): 2, (2, 'a'): 1, (2, 'b'): 2}

In [4]: F
Out[4]: 2

编辑

使用您 运行ning 的新代码,罪魁祸首是循环中的除法运算:t/a。这个 return 默认是一个浮点数,而在 Python 2 中,如果 ta 都是整数,它将 return 一个整数。在 Python 3 环境中,您必须小心 运行ning Python 2 代码。只需将 t/a 包装在 int 调用中:int(t/a).

In [7]: S,D,F=eval(input())
   ...: s=1
   ...: for c in S:
   ...:  t,s=s,0
   ...:  for a,b in D[c]:s|=int(t/a)%2*b
   ...: print(["Not a chance!","Accepted!"][F&s>0])
   ...:
'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2
Accepted!

我最后要提醒您的是,在 Python 3 环境中要格外小心 运行ning Python 2 代码。如果可能,运行 其设计环境中的代码。如果没有,这个有用的成语比较指南从 Python 2 到 Python 3 应该有所帮助:http://python-future.org/compatible_idioms.html。特别是: