-1

I have to implement a function that checks if a query string is accepted by the FSM (Finite State Automata) down below

FSM

I have already made a small design that basically retrieves all the data which is needed to work with. I still need to implement code that checks for each character in the query_string if it is available in the certain arrow (transition).

So we have for example the query string 'aab' The way the code must run is that it checks if the first character in the query is available in a transition from q0 to q1. In this case that's true so then the code needs to go and check if the second character in the query is present in the transitions going from q1 to q2. This is true again. But then there are no transitions left so the third character in the query is not present in any transitions and it needs to return false. If the query string is accepted the code must return True I'm pretty new to this so I hope you can understand this code down below

Code:

def accept(fsm, query_string):
query_list = list(query_string)
# this is the list of the query string
print(query_list)

start = fsm1.get_initial_state()
betweenstates = fsm1.get_transitions()
endstates = fsm1.get_end_states()

# this function iterates through a dictionary and gives the available transtions per state
for i,j in betweenstates.items():
    print("The transition to the next state" + str(i) + " : ")
    for k in tuple(j):
        print(k)

return False

print('This is the first query_string')
# This is the function that is ran
print(accept(fsm1, "b"))   # should be True
print('\n')
print('This is the second query_string')
print(accept(fsm1, "aab")) # should be False

This is the output:

This is the first query_string
['b']
First entries for Q0 : 
('a', 'Q1')
('b', 'Q1')
First entries for Q1 : 
('a', 'Q2')
('', 'Q2')
('b', 'Q2')
False


This is the second query_string
['a', 'a', 'b']
First entries for Q0 : 
('a', 'Q1')
('b', 'Q1')
First entries for Q1 : 
('a', 'Q2')
('', 'Q2')
('b', 'Q2')
False

1 Answers1

2

Coding a finite state machine is pretty easy:

It takes three components.

  1. A set of states (list of ints)
  2. A set of final-states (list of ints)
  3. A transition matrix (3d array of bools (state_old, state_new, char)). (An epsilon edge simply means that all transitions are valid)

Then create a function that recursively calls itself. This function takes a string as input, the current state, and both sets of states and the transition table. If the string is empty it returns true if state is a final state and false if state is not final. If the string is not empty it checks the entry in the transition table for passed state and string[0] and calls itself with but this time with string[1:] and the new state.

Thats pretty much it. I did not put any code in here on purpose because it is a pretty good exercise to do this on your own.

Jonathan R
  • 3,652
  • 3
  • 22
  • 40