-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathex6.py
65 lines (58 loc) · 1.33 KB
/
ex6.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
a = ["E=E+T",
"E=T",
"T=T*F",
"T=F",
"F=(E)",
"F=i"]
rules = {}
terms = []
for i in a:
temp = i.split("=")
terms.append(temp[0])
try:
rules[temp[0]] += [temp[1]]
except:
rules[temp[0]] = [temp[1]]
terms = list(set(terms))
print(rules,terms)
def leading(gram, rules, term, start):
s = []
if gram[0] not in terms:
return gram[0]
elif len(gram) == 1:
return [0]
elif gram[1] not in terms and gram[-1] is not start:
for i in rules[gram[-1]]:
s+= leading(i, rules, gram[-1], start)
s+= [gram[1]]
return s
def trailing(gram, rules, term, start):
s = []
if gram[-1] not in terms:
return gram[-1]
elif len(gram) == 1:
return [0]
elif gram[-2] not in terms and gram[-1] is not start:
for i in rules[gram[-1]]:
s+= trailing(i, rules, gram[-1], start)
s+= [gram[-2]]
return s
leads = {}
trails = {}
for i in terms:
s = [0]
for j in rules[i]:
s+=leading(j,rules,i,i)
s = set(s)
s.remove(0)
leads[i] = s
s = [0]
for j in rules[i]:
s+=trailing(j,rules,i,i)
s = set(s)
s.remove(0)
trails[i] = s
for i in terms:
print("LEADING("+i+"):",leads[i])
for i in terms:
print("TRAILING("+i+"):",trails[i])