Finite State Machines Part I State Based Computing
State-based Reasoning The state of a computation is all the internal information needed to take the next step in the computation 0 NEWx -> S 1 previous state next state external input data literal next step (action)
Picobot == state machine each oval represents a different robot state Semantic action ***x/ move S x***/move N N*** state pattern -> move new state start here state 0 state 1 0 x*** -> N 0 0 N*** -> X 1 1 ***x -> S 1 1 ***S -> X 0 the "go North" state the "go South" state ***S transitions move from state to state
All computation can be considered a deliberate sequence of state-changes 0110110101011010010001 0110110101000000001110 bits before bits after
A model of computation: FSM FSM or Finite State Machine Example: 1 s0 s1 1 start state transitions accepting states Don't give the answer of what each state means yet… two slides away! “input funnel” “where to go” double circled labeled by input ! How it runs: 100101 input sequence read left-to-right
Parts of a Finite State Machine (FSM) 1. Must have a finite number of states, i.e., can't be an infinite number. Drawn as circles with label. 2. Must have one starting state designated by 3. Have a non empty subset of the states called final or accepting states designated by double circles. 4. Have transitions of how to change from one state to another state. Drawn as arrows labeled with the input character read. 5. Rule of acceptance: If on reading the last input character the FSM is in a final state, the FSM accepts, otherwise rejects. s0 s1 0,1 s0 s1 FSM accepts all binary strings with at least one 1. 1
0010111 FSM: Finite state machine State 1 State 0 transition on 0 Oh, how I wish we could discuss regex! State 0 – Even number of 1s seen so far State 1 – Odd 1s This accepts sequences of any string with an odd number of 1s another input sequence 0010111 What does each state MEAN ? What does this FSM do overall? always left-to-right
How to Program a FSM? "Count the words in a file" example FSMs great for design of character processing problems Translation to Python program mechanical!
How to Program a FSM? state = 'WS' # start state for FSM words = 0 # action done at start of FSM for line in file1: for ch in line: # FSM-For each character read, depending on character read #and current state, change to new state and do any actions. if state == 'WS': if isWhitespace(ch): state = 'WS' else: state = 'WORD' words += 1 # action elif state == 'WORD': print('Should not be here! Must be programming error!') # End of FSM