Feat: Better typing in inverter.py
This commit is contained in:
+12
-4
@@ -1,11 +1,19 @@
|
|||||||
|
from typing import Tuple, TypedDict
|
||||||
|
|
||||||
from snanosm.mealy import Machine
|
from snanosm.mealy import Machine
|
||||||
|
|
||||||
|
class Context(TypedDict):
|
||||||
|
result: str
|
||||||
|
n_chars: int
|
||||||
|
|
||||||
def add_to_result(context, c):
|
def add_to_result(context, c):
|
||||||
context["result"] += c
|
context["result"] += c
|
||||||
|
context["n_chars"] += 1
|
||||||
|
|
||||||
def inverter(input_string: str) -> str:
|
def inverter(input_string: str) -> Tuple[str, int]:
|
||||||
context = {
|
context: Context = {
|
||||||
"result": ""
|
"result": "",
|
||||||
|
"n_chars": 0
|
||||||
}
|
}
|
||||||
m = Machine(context)
|
m = Machine(context)
|
||||||
m.add_state("S", True, False)
|
m.add_state("S", True, False)
|
||||||
@@ -13,7 +21,7 @@ def inverter(input_string: str) -> str:
|
|||||||
m.add_transition("1", "S", "S", lambda ctx: add_to_result(ctx, "0"))
|
m.add_transition("1", "S", "S", lambda ctx: add_to_result(ctx, "0"))
|
||||||
for c in input_string:
|
for c in input_string:
|
||||||
m.process_input(c)
|
m.process_input(c)
|
||||||
return context["result"]
|
return context["result"], context["n_chars"]
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
print(inverter("000011110010"))
|
print(inverter("000011110010"))
|
||||||
Reference in New Issue
Block a user