forked from PratikSavla/compiler-design-lab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex8.py
41 lines (38 loc) · 917 Bytes
/
ex8.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
# example 1
gram = {
"E":["2E2","3E3","4"]
}
starting_terminal = "E"
inp = "2324232$"
"""
# example 2
gram = {
"S":["S+S","S*S","i"]
}
starting_terminal = "S"
inp = "i+i*i"
"""
stack = "$"
print(f'{"Stack": <15}'+"|"+f'{"Input Buffer": <15}'+"|"+f'Parsing Action')
print(f'{"-":-<50}')
while True:
action = True
i = 0
while i<len(gram[starting_terminal]):
if gram[starting_terminal][i] in stack:
stack = stack.replace(gram[starting_terminal][i],starting_terminal)
print(f'{stack: <15}'+"|"+f'{inp: <15}'+"|"+f'Reduce S->{gram[starting_terminal][i]}')
i=-1
action = False
i+=1
if len(inp)>1:
stack+=inp[0]
inp=inp[1:]
print(f'{stack: <15}'+"|"+f'{inp: <15}'+"|"+f'Shift')
action = False
if inp == "$" and stack == ("$"+starting_terminal):
print(f'{stack: <15}'+"|"+f'{inp: <15}'+"|"+f'Accepted')
break
if action:
print(f'{stack: <15}'+"|"+f'{inp: <15}'+"|"+f'Rejected')
break