Files
snanosm/examples/inverter.py
T

27 lines
738 B
Python

from typing import Tuple, TypedDict
from snanosm.mealy import Machine
class Context(TypedDict):
result: str
n_chars: int
def add_to_result(context: Context, c: str) -> None:
context["result"] += c
context["n_chars"] += 1
def inverter(input_string: str) -> Tuple[str, int]:
context: Context = {
"result": "",
"n_chars": 0
}
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)
return context["result"], context["n_chars"]
if __name__ == '__main__':
print(inverter("000011110010"))