In: Computer Science
Write a python function to fulfill the requirements. The function accepts a string, a current state, edges’ information, and an accepting state. The output of the function is a boolean value verifying if the string can pass the finite state machine or not.
### Finite State Machine Simulator in Python
### Provide s1 and s2 that are both accepted, but s1 != s2.
s1 = "bdf"
s2 = "bdgbdf"
edges = {(1,'a') : 2,
(1,'b') : 3,
(2,'c') : 4,
(3,'d') : 5,
(5,'c') : 2,
(5,'f') : 6,
(5,'g') : 1}
accepting = [6]
def fsmsim(string, current, edges, accepting):
### Your code here.
### Test the function
print(fsmsim(s1,1,edges,accepting))
# >>> True
print(fsmsim(s2,1,edges,accepting))
# >>> True
print(s1 != s2)
# >>> True
Python program :
def fsmsim(string, current , edges, accepting):
for s in string: # iterate through all characters in string
state = edges[current,s] # go to the next state by traversing on the given current state and character in string
current = state
if(current == accepting[0]): # check if both the state we got in current is equal to the accepting
return True # return true if accepting
else:
return False # return false if not accepting
s1 = "bdf"
s2 = "bdgbdf"
edges = {(1,'a') : 2, (1,'b') : 3, (2,'c') : 4, (3,'d') : 5, (5,'c') : 2, (5,'f') : 6, (5,'g') : 1}
accepting = [6]
print(fsmsim(s1,1,edges,accepting)) # returns True as final state is accepting state
print(fsmsim(s2,1,edges,accepting)) # returns True as final state is accepting state
print(s1 != s2) # return True as both strings are not equal
Screenshot :