forked from MaximHirschmann/CYK-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcyk.py
More file actions
76 lines (63 loc) · 1.98 KB
/
cyk.py
File metadata and controls
76 lines (63 loc) · 1.98 KB
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
word = "baaba"
G = """
S -> AB | BC
A -> BA | a
B -> CC | b
C -> AB | a
"""
def inputToGrammar(inp):
res = {}
for line in inp.split("\n"):
if line == "\n":
continue
line = line.replace(" ", "")
splitted = line.split("->")
if len(splitted) < 2:
continue
v = splitted[0]
right = splitted[1]
res[v] = []
for possibility in right.split("|"):
res[v].append(possibility)
return res
def printer(word, table):
space = 30
print("CYK".ljust(space) + "| ", end = "")
for i in range(len(word)):
print(str(i+1).ljust(space), end = "")
print()
print("-"*((len(word)+1)*space+2))
for i in range(len(word)):
print((str(i+1)+ ": "+ word[i]).ljust(space) + "| ", end="")
for j in range(len(word)):
if i + j <= len(word)-1:
string = table[i][j].__repr__()
if string == "set()":
print("{}".ljust(space), end = "")
else:
print(string.ljust(space), end = "")
else:
print(" "*space, end = "")
print()
from itertools import product
G2 = inputToGrammar(G)
table = [[set() for _ in range(len(word))] for __ in range(len(word))]
for length in range(1, len(word)+1):
for i in range(len(word)-length+1):
searches = []
if length == 1:
searches.append(word[i])
else:
for newLength in range(1, length):
l1 = word[i:i+newLength]
l2 = word[i+newLength:i+length]
v1 = table[i][newLength-1]
v2 = table[i+newLength][length-newLength-1]
searches += [''.join(i) for i in product(*[v1, v2])]
for k, v in G2.items():
for res in v:
for s in searches:
if s == res:
table[i][length-1].add(k)
printer(word, table)
quit = input("Press Enter to exit")