Files
snanosm/examples/inverter.py
T

27 lines
738 B
Python
Raw Normal View History

2026-07-16 10:45:02 +03:00
from typing import Tuple, TypedDict
2026-07-15 17:40:33 +03:00
from snanosm.mealy import Machine
2026-07-16 10:45:02 +03:00
class Context(TypedDict):
result: str
n_chars: int
2026-07-16 10:48:27 +03:00
def add_to_result(context: Context, c: str) -> None:
2026-07-15 17:40:33 +03:00
context["result"] += c
2026-07-16 10:45:02 +03:00
context["n_chars"] += 1
2026-07-15 17:40:33 +03:00
2026-07-16 10:45:02 +03:00
def inverter(input_string: str) -> Tuple[str, int]:
context: Context = {
"result": "",
"n_chars": 0
2026-07-15 17:40:33 +03:00
}
m = Machine(context)
m.add_state("S", True, False)
m.add_transition("0", "S", "S", lambda ctx: add_to_result(ctx, "1"))
m.add_transition("1", "S", "S", lambda ctx: add_to_result(ctx, "0"))
for c in input_string:
m.process_input(c)
2026-07-16 10:45:02 +03:00
return context["result"], context["n_chars"]
2026-07-15 17:40:33 +03:00
if __name__ == '__main__':
print(inverter("000011110010"))