-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathExample_10.py
127 lines (109 loc) · 2.14 KB
/
Example_10.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
125
126
127
#!/usr/bin/python3
# Implement Elimination of Left Recursion
gram = {}
def add(str): #to rules together
x = str.split("->")
y = x[1]
x.pop()
z = y.split("|")
x.append(z)
gram[x[0]]=x[1]
def removeDirectLR(gramA, A):
"""gramA is dictonary"""
temp = gramA[A]
tempCr = []
tempInCr = []
for i in temp:
if i[0] == A:
#tempInCr.append(i[1:])
tempInCr.append(i[1:]+[A+"'"])
else:
#tempCr.append(i)
tempCr.append(i+[A+"'"])
tempInCr.append(["e"])
gramA[A] = tempCr
gramA[A+"'"] = tempInCr
return gramA
def checkForIndirect(gramA, a, ai):
if ai not in gramA:
return False
if a == ai:
return True
for i in gramA[ai]:
if i[0] == ai:
return False
if i[0] in gramA:
return checkForIndirect(gramA, a, i[0])
return False
def rep(gramA, A):
temp = gramA[A]
newTemp = []
for i in temp:
if checkForIndirect(gramA, A, i[0]):
t = []
for k in gramA[i[0]]:
t=[]
t+=k
t+=i[1:]
newTemp.append(t)
else:
newTemp.append(i)
gramA[A] = newTemp
return gramA
def rem(gram):
c = 1
conv = {}
gramA = {}
revconv = {}
for j in gram:
conv[j] = "A"+str(c)
gramA["A"+str(c)] = []
c+=1
for i in gram:
for j in gram[i]:
temp = []
for k in j:
if k in conv:
temp.append(conv[k])
else:
temp.append(k)
gramA[conv[i]].append(temp)
#print(gramA)
for i in range(c-1,0,-1):
ai = "A"+str(i)
for j in range(0,i):
aj = gramA[ai][0][0]
if ai!=aj :
if aj in gramA and checkForIndirect(gramA,ai,aj):
gramA = rep(gramA, ai)
for i in range(1,c):
ai = "A"+str(i)
for j in gramA[ai]:
if ai==j[0]:
gramA = removeDirectLR(gramA, ai)
break
op = {}
for i in gramA:
a = str(i)
for j in conv:
a = a.replace(conv[j],j)
revconv[i] = a
for i in gramA:
l = []
for j in gramA[i]:
k = []
for m in j:
if m in revconv:
k.append(m.replace(m,revconv[m]))
else:
k.append(m)
l.append(k)
op[revconv[i]] = l
return op
n = int(input("Enter No of Production: "))
for i in range(n):
txt=input()
add(txt)
result = rem(gram)
for x,y in result.items():
print(f'{x} -> {y}')