-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate_machine_v5.py
executable file
·53 lines (42 loc) · 1.44 KB
/
state_machine_v5.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
from typing import TypeVar, Callable, List, FrozenSet, Generic
I = TypeVar('I')
S = TypeVar('S')
class StateMachine(Generic[I,S]):
def __init__(self
, states : FrozenSet[S]
, initial_state : S
, input_alphabet : FrozenSet[I]
, transition : Callable[[S,I],S]):
if initial_state not in states:
raise ValueError("Invalid initial state")
self.states = states
self.state = initial_state
self.input_alphabet = input_alphabet
self.transition = transition
def run(self, input : List[I]):
for c in input:
if c in self.input_alphabet:
self.state = self.transition(self.state,c)
else:
raise ValueError(f"{c} not in input alphabet!")
# Even Binary
input1 = "10001110101010101" # 9 -- Odd
input2 = "" # 0 -- Even
input3 = "01010110101001000110" # 9 -- Odd
input4 = "10110001" # 4 -- Even
def evenBinaryTransition(state : str, input : str):
if state == "even":
if input == "1":
return "odd"
else:
return "even"
else:
if input == "1":
return "even"
else:
return "odd"
machine = StateMachine(frozenset(["even", "odd"])
, "even"
, frozenset(["1","0"])
, evenBinaryTransition)