Created
December 29, 2023 11:12
-
-
Save DuskyElf/18aba4aafe58e0cf0831db80bd7018ff to your computer and use it in GitHub Desktop.
Super simple Mealy machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from __future__ import annotations | |
| InputSym = int # 0 or 1 | |
| OutputSym = str # from State.output | |
| class State: | |
| def __init__(self, name: str) -> None: | |
| self.name = name | |
| self.sigma = [0, 1] | |
| self.output = ["a", "b"] | |
| self.next: dict[InputSym, tuple[State, OutputSym]] = {} | |
| def delta(self, i: InputSym) -> tuple[State, OutputSym]: | |
| return self.next[i] | |
| def set_transition(self, i: InputSym, s: State, o: OutputSym) -> None: | |
| self.next[i] = (s, o) | |
| def __str__(self): | |
| return self.name | |
| class Mealy: | |
| def __init__(self, q: list[State]) -> None: | |
| self.q = q | |
| def delta(self, s: str) -> str: | |
| result = "" | |
| state = self.q[0] | |
| for current_symbol in s: | |
| next_state, output = state.delta(int(current_symbol)) | |
| print(f"d({state}, {current_symbol}) = {next_state}") | |
| print(output) | |
| result += output | |
| state = next_state | |
| return result | |
| def main(): | |
| A = State("A") | |
| B = State("B") | |
| C = State("C") | |
| A.set_transition(1, A, "b") | |
| A.set_transition(0, B, "b") | |
| B.set_transition(0, B, "b") | |
| B.set_transition(1, C, "a") | |
| C.set_transition(0, B, "b") | |
| C.set_transition(1, A, "b") | |
| m = Mealy([A, B]) | |
| print(m.delta("10100")) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment