[英]Deterministic Finite Automata (DFA) Implementation
I need to build a state machine and write a control program to recognise a set of strings of zeros and ones, in which there are three zeros between each occurrence of one.我需要构建一台 state 机器并编写一个控制程序来识别一组由 0 和 1 组成的字符串,其中每个出现的 1 之间有 3 个 0。 Below is my code which is not working correctly.下面是我的代码,它不能正常工作。 I will be grateful for the advice我将不胜感激
Z = ["0", "1"]
Q = ["A", "B"]
S = "A"
F = "B"
def delta(s, z):
i = Q.index(s)
j = Z.index(z)
matrix = [["A", "B"], ["B", "A"]]
return matrix[i][j]
chain = "1000110110101"
transitions = ""
for char in range(len(chain)):
if char == 0:
transitions += S
s = delta(S, chain[char])
else:
s = delta(s, chain[char])
transitions += s
if transitions != "":
print("The sequence of transitions of a finite automaton:", transitions)
if transitions[-1] == F:
print("Chain ", chain, "is allowed automaton, because the latter is the allowable state ", F)
else:
print("Chain ", chain, " is rejected by the automaton, so its final state is an inadmissible state", S)
else:
print("The chain is empty.")
You might not have been introduced to classes yet but I would definitely recommend using them for DFAs.您可能还没有接触过类,但我肯定会推荐将它们用于 DFA。
class binaryNode:
def __init__(self):
self.zero = self
self.one = self
self.isAccept = True
def process(self,char):
if char == "0":
return self.zero
if char == "1":
return self.one
#Define Nodes
start = binaryNode()
one = binaryNode()
firstZero = binaryNode()
secondZero = binaryNode()
thirdZero = binaryNode()
trailingZero = binaryNode()
reject = binaryNode()
#Define Edges
start.one = one
one.one = reject
one.zero = firstZero
firstZero.zero = secondZero
firstZero.one = reject
secondZero.zero = thirdZero
secondZero.one = reject
thirdZero.one = one
thirdZero.zero = trailingZero
trailingZero.one = reject
#Set Accept (or in this case reject) state
reject.isAccept = False
def process(chain,node):
for char in chain:
node = node.process(char)
return node.isAccept
tests = ["0000",
"01000100",
"0100010001000100",
"0100001",
"100101",
"10001",
"10000"]
for chain in tests:
print(chain)
print(process(chain,start))
print()
I interpreted your "recognize a set of strings of zeros and ones, in which there are three zeros between each occurrence of one" with a focus on between so 100000000 passes and so does 100 because there is no second 1 to satisfy the "between" aspect but perhaps I'm misinterpreting.我解释了你的“识别一组零和一的字符串,其中每次出现的一个之间有三个零”,重点放在 100000000 次之间,100 次也是如此,因为没有第二个 1 来满足“之间”方面,但也许我误解了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.