Finite Automata: Definition, How It Works, and Examples
Finite automata are simple machines used in computer science to recognize patterns or sequences of symbols. They work by moving through a limited set of states based on input symbols, deciding if the input is accepted or rejected.How It Works
Imagine a vending machine that accepts coins and dispenses snacks. It has a few states like "waiting for coin", "coin inserted", and "dispense snack". Depending on the coin you insert, it moves from one state to another. Similarly, a finite automaton has a fixed number of states and reads input symbols one by one. For each symbol, it changes its state according to predefined rules.
At the end of the input, if the automaton is in a special "accept" state, it means the input matches the pattern it recognizes. Otherwise, the input is rejected. This simple mechanism helps computers quickly check if strings follow certain rules, like valid words or commands.
Example
This example shows a finite automaton that accepts strings containing an even number of zeros.
class FiniteAutomaton: def __init__(self): self.state = 'even' def process(self, input_string: str) -> bool: for char in input_string: if char == '0': self.state = 'odd' if self.state == 'even' else 'even' elif char != '1': return False # invalid character return self.state == 'even' fa = FiniteAutomaton() print(fa.process('1100')) # True print(fa.process('1010')) # True print(fa.process('100')) # False print(fa.process('abc')) # False
When to Use
Finite automata are useful when you need to quickly check if input matches simple patterns. They are widely used in compilers to recognize tokens like keywords, numbers, or identifiers. For example, when you write code, the compiler uses finite automata to break your code into meaningful pieces.
They are also used in text search tools, network protocol design, and anywhere pattern matching is needed with limited memory and fast processing.
Key Points
- Finite automata have a limited number of states.
- They read input symbols one at a time and change states accordingly.
- They decide if input is accepted based on the final state.
- Used in compilers for token recognition and pattern matching.
- Simple, fast, and memory-efficient machines.