Python Advanced - Finite State Machine in Python

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Python Advanced Course

Topics

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Currying in Python


Next Chapter: Turing Machine in Python

Finite State Machine (FSM)


A "Finite State Machine" (abbreviated FSM), also called "State
Machine" or "Finite State Automaton" is an abstract machine which
consists of a set of states (including the initial state and one or Help Needed
more end states), a set of input events, a set of output events,
and a state transition function. A transition function takes the This website is free
Advanced current state and an input event as an input and returns the new of annoying ads. We
set of output events and the next (new) state. Some of the states
Topics are used as "terminal states".
want to keep it like
this. You can help
Introduction into with your donation:
The operation of an FSM begins with a special state, called the
the sys module start state, proceeds through transitions depending on input to
Python and the different states and normally ends in terminal or end states. A
Shell state which marks a successful flow of operation is known as an The need for
Forks and accept state. donations
Forking in
Python Mathematical Model:
A deterministic finite state machine or acceptor deterministic finite Job Applications
Introduction into
state machine is a quintuple
Threads
(Σ,S,s0,δ,F),
Pipe, Pipes and Python
where:
"99 Bottles of Σ is the input alphabet (a finite, non-empty set of symbols). Lecturer
Beer" S is a finite, non-empty set of states. bodenseo is
Python Network s0 is an initial state, an element of S. looking for a
Scanner δ is the state-transition function: δ : S x Σ → S new trainer
Graph Theory (in a nondeterministic finite state machine it would be δ : S x Σ → ℘(S), i.e., δ would return a set of and software
and Graphs in states). (℘(S) is the Power set of S) developper.
Python You need to
F is the set of final states, a (possibly empty) subset of S.
Graphs: live in
PyGraph Germany and
A Simple Example
know German.
Graphs We want to recognize the meaning of very small sentences with an extremely limited vocabulary and
Interested?
A Python Class syntax:
Find out more!
for Polynomial These sentences should start with "Python is" followed by
Functions an adjective or CSS-help
Currying in the word "not" followed by an adjective. needed!
Python
Finite State e.g. We urgently
Machine in "Python is great" → positive meaning need help to
"Python is stupid" → negative meaning improve our
Python
"Python is not ugly" → positive meaning css style
Turing Machine
sheets,
in Python
especially to
Levenshtein improve the
Distance look when
Example for printing! Best
recursive would be, if we
Programming: find somebody
Towers of Hanoi who wants to
Mastermind / do it for free to
support our
Bulls and Cows
website. But
Creating we could also
dynamic pay something.
websites with Please contact
WSGI us, if you think
Dynamic that you could
websites with be of help!
mod_python
Dynamic
websites with Bernd Klein on
Pylons Facebook
Python, SQL,
MySQL and
SQLite
Python Scores Search this website:
A Finite State Machine in Python
Go

To implement the previous example, we program first a general Finite State Machine in Python. We save
this class as statemachine.py: This topic in German
Help Needed / Deutsche
class StateMachine: Übersetzung:
This website is free def __init__(self): Endliche Automaten
of annoying ads. We self.handlers = {} in Python
want to keep it like self.startState = None
this. You can help self.endStates = []
Python Training
with your donation: Courses
def add_state(self, name, handler, end_state=0):
name = name.upper()
self.handlers[name] = handler If you want to learn
The need for if end_state: Python fast and
donations self.endStates.append(name) efficiently, the right
step will be a
def set_start(self, name): Python Training
self.startState = name.upper() course at Bodenseo.
Wisdom There are also
def run(self, cargo): special seminars for
try:
"The infinite is in the advanced students
handler = self.handlers[self.startState]
finite of every like the Python &
except:
instant" (Zen XML Training Course.
raise InitializationError("must call .set_start() before .run()")
proverb) if not self.endStates: If you want to
raise InitializationError("at least one state must be an end_state") acquire special
*** knowledge in Text
while True: Processing and Text
"No finite point has (newState, cargo) = handler(cargo) Classification, then
meaning without an if newState.upper() in self.endStates: "Python Text
infinite reference print("reached ", newState) Processing Course"
point" (Jean-Paul break will be the right one
Sartre)
else: for you.
handler = self.handlers[newState.upper()] All the Python
*** seminars are
This general FSM is used in the next program: available in German
"Ask what Time is, it as well: Python-
from statemachine import StateMachine Kurse"
is nothing else but
something of eternal positive_adjectives = ["great","super", "fun", "entertaining", "easy"]
duration become negative_adjectives = ["boring", "difficult", "ugly", "bad"]
finite, measurable
and transitory." def start_transitions(txt):
(William Law) splitted_txt = txt.split(None,1)
word, txt = splitted_txt if len(splitted_txt) > 1 else (txt,"")
if word == "Python":
newState = "Python_state"
"The machine does else: Python Courses at
not isolate us from newState = "error_state" Bodenseo.
the great problems return (newState, txt)
of nature but You can book Bernd
def python_state_transitions(txt): Klein for on-site
plunges us more
splitted_txt = txt.split(None,1) Python courses as
deeply into them"
word, txt = splitted_txt if len(splitted_txt) > 1 else (txt,"") well.
(Antoine de Saint- if word == "is":
Exupery) newState = "is_state"
else:
*** newState = "error_state" Text
return (newState, txt) Classification
"A tool is but the
extension of a man's def is_state_transitions(txt): Though the
hand, and a machine splitted_txt = txt.split(None,1) automated
is but a complex word, txt = splitted_txt if len(splitted_txt) > 1 else (txt,"") classification
tool. And he that if word == "not": (categorization) of
invents a machine newState = "not_state"
texts has been
augments the power elif word in positive_adjectives:
flourishing in the last
of a man and the newState = "pos_state"
elif word in negative_adjectives: decade, it has a
well-being of history, which dates
newState = "neg_state"
mankind." (Henry back to about 1960.
else:
Ward Beecher) The incredible
newState = "error_state"
return (newState, txt) increase in online
documents, which
This website is def not_state_transitions(txt): has been mostly due
supported by: splitted_txt = txt.split(None,1) to the expanding
word, txt = splitted_txt if len(splitted_txt) > 1 else (txt,"") internet, has
Python Training if word in positive_adjectives: renewed the interst
Courses newState = "neg_state" in automated
elif word in negative_adjectives: document
newState = "pos_state" classification and
else: data mining. While
newState = "error_state"
text classification in
return (newState, txt)
the beginning was
def neg_state(txt): based mainly on
print("Hallo") heuristic methods,
return ("neg_state", "") i.e. applying a set of
rules based on
if __name__== "__main__": expert knowledge,
m = StateMachine() nowadays the focus
m.add_state("Start", start_transitions) has turned to fully
m.add_state("Python_state", python_state_transitions) automatic learning
m.add_state("is_state", is_state_transitions) and even clustering
m.add_state("not_state", not_state_transitions) methods.
m.add_state("neg_state", None, end_state=1)
m.add_state("pos_state", None, end_state=1)
m.add_state("error_state", None, end_state=1)
m.set_start("Start")
m.run("Python is great")
Help Needed
m.run("Python is difficult")
m.run("Perl is ugly")
This website is free
If we save the application of our general Finite State Machine in statemachine_test.py and call it with of annoying ads. We
want to keep it like
python statemachine_test.py this. You can help
with your donation:
we get the following results:

$ python statemachine_test.py
The need for
reached pos_state which is an end state
reached neg_state which is an end state donations
reached error_state which is an end state

The code of the finite state machine is compatible with Python3 as well! Data Protection
Previous Chapter: Currying in Python Declaration
Next Chapter: Turing Machine in Python
Data Protection
Declaration

© 2011 - 2020, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like