class DFA: current_state = None; def __init__(self, states, alphabet, transition_function, start_state): self.states = states; self.alphabet = alphabet; self.transition_function = transition_function; self.start_state = start_state; self.current_state = start_state; return; # Move to a new state given an input def transition_to_state_with_input(self, input_value): # Do we have a rule to move from the current state to somewhere else based on the input_value? # if not, we should freak out if ((self.current_state, input_value) not in self.transition_function.keys()): self.current_state = None; return; # else, the current state becomes whatever is defined in the transition_function. self.current_state = self.transition_function[(self.current_state, input_value)]; return; # Reset to the start state def go_to_initial_state(self): self.current_state = self.start_state; return; def __str__(self): "The current_state is: " + self.current_state; # Homework :P # def run_with_input_list(self, input_list): # This one is for you to figure out, given a list of moods, go through all the necessary transitions. states = {'Neutral', 'Happy', 'Sad', 'Focus'}; alphabet = {'Happy', 'Sad', 'Focus'}; transitions_map = dict(); transitions_map[('Neutral', 'Happy')] = 'Happy'; transitions_map[('Neutral', 'Sad')] = 'Sad'; transitions_map[('Neutral', 'Focus')] = 'Focus'; transitions_map[('Happy', 'Sad')] = 'Neutral'; transitions_map[('Sad', 'Happy')] = 'Neutral'; start_state = 'Neutral'; d = DFA(states, alphabet, transitions_map, start_state); print d; d.transition_to_state_with_input('Happy'); print d; d.transition_to_state_with_input('Sad'); print d;
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question