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. 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.