# https://en.wikipedia.org/wiki/Deterministic_finite_automaton class DFA: #Deterministic Finite Automaton def __init__ (self ,states : set , alphabets : set, transition_function , initial , accepted_states : set): self.states = states self.alphabets = alphabets if (self.__checkTransitionFunction__(transition_function)): self.transitionFunction = transition_function else : print ("Error: The Transition function has some errors") if (self.__checkInitialState__(initial)): self.initialState = initial else : print ("Error: The initial states in not in all valid states. Here states =", self.states) if (self.__checkAcceptedStates__(accepted_states)): self.acceptedStates = accepted_states else: print("Error: The accepted states are not in all valid states. Here states are =" , self.states) def __checkInitialState__ (self , initalState): return initalState in self.states def __checkAcceptedStates__ (self , accepted_states): return accepted_states.issubset(self.states) def __checkTransitionFunction__(self, transition_function): def checkKey(key): return len(key)==2 and key[0] in self.states and key[1] in self.alphabets if (set (transition_function.values()).issubset(self.states)): for key in transition_function : if not checkKey(key): return False else: return True def getFinalState (self , inputData): currentState = self.initialState for input in inputData: if (input not in self.alphabets): print ("Input is not from the Alphabets") break currentState = self.transitionFunction.get((currentState, input) , None) if currentState == None: print("Error: The Transition Function do not have state for currentState: ", currentState , "input: ", input ) return currentState def isAccepted (self , input): return self.getFinalState(input) in self.acceptedStates