Description

State machines are methods for updating the state that a system is in and safely moving to a new one.

Runtime

O(n)

Visualization

This is the State machine to validate that a string is a number
Pasted image 20250315102603.png

Pseudocode

create a set of states by drawing a diagram and how you move from each state to the next
Start at the first state with the first item to consume and go to the next spot

Code

def state_function(value):
    return value, next_state_function

def error(value):
    return value, error

def is_done(value):
    return value == ""

class StateMachine:
    def __init__(self, start_state, end_states, error_states, is_done):
        self.start_state = start_state
        self.end_states = set(end_states)
        self.error_states = set(error_states)
        self.is_done = is_done

    def consume(self, value):
        state = self.start_state
        while not state in self.error_states and not self.is_done(value):
            value, state = state(value)
        return state in self.end_states

StateMachine(
    start_state=state_function,
    end_states=[state_function],
    error_states=[error],
    is_done=is_done,
)