-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
124 lines (107 loc) · 3.33 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
class Equation:
def __init__(self, var, st):
self.var = var
self.st = st
self.nextOpt = None
self.next = None
def add(self, opt, var, st):
top = self
while top.var != var and top.next is not None:
top = top.next
if top.var == var:
top.st = f"({top.st}{opt}{st})"
else:
top.nextOpt = opt
top.next = Equation(var, st)
def substitute(self, name):
top = self
while top:
if top.var != name:
top.st = f"{self.var}"
def ardenTheorem(self, name):
top = self
prev = None
while top.var != name and top.next is not None:
prev = top
top = top.next
if top.var == name:
tmp = top.st
if prev is None:
self.__dict__.update(self.next.__dict__)
else:
prev.next = top.next
self.printEqn(name)
top = self
while top is not None:
top.st += f"({tmp})*"
top = top.next
def printEqn(self, name):
s = f"{name} = ({self.var}){self.st}"
top = self
while top.next is not None:
s += f" {top.nextOpt} "
top = top.next
s += f"({top.var}){top.st}"
print(s)
class StateDiagram:
def __init__(self):
self.states = []
self.terminals = []
self.start = None
self.final = []
self.transition = {}
def listInput(self, l):
print("Enter N to stop")
s = input()
while s != "N":
l.append(s)
s = input()
return l
def inputTransition(self):
print("Format : present:terminal>next")
print("Enter N to stop")
s = input()
while s != 'N':
s = s.replace('>', ':').split(':')
if s[2] in self.transition:
self.transition[s[2]].add('+', s[0], s[1])
else:
self.transition[s[2]] = Equation(s[0], s[1])
s = input()
self.transition[self.start].add('+', '$', '')
def input(self):
print("Enter the states:")
self.listInput(self.states)
print("Enter the terminals:")
self.listInput(self.terminals)
print("Enter the start symbol:")
self.start = input()
print("Enter the final state:")
self.listInput(self.final)
print("Enter the transition rules")
self.inputTransition()
def genRegEx(self):
for i in self.final:
self.transition[i].substitute()
self.transition[i].ardenTheorem()
s = self.final[0]
for i in self.final[1:]:
s += f" + {i}"
s += f"{self.transition[0].st}"
for i in self.final[1:]:
s += f" + {self.transition[i].st}"
print(s)
def display(self):
print(f"Q : {self.states}")
print(f"Sigma : {self.terminals}")
print("Transition Equations")
for i in self.transition.keys():
self.transition[i].printEqn(i)
# print(f"{i} = ({self.transition[i].var}){self.transition[i].st}")
print(f"Q0 : {self.start}")
print(f"F : {self.final}")
if __name__ == "__main__":
sd = StateDiagram()
sd.input()
sd.display()
sd.genRegEx()