-
Notifications
You must be signed in to change notification settings - Fork 0
/
bonus1.py
94 lines (84 loc) · 2.04 KB
/
bonus1.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
#!/usr/bin/python
#!python
#import os
import Queue
#from IPython.core.debugger import Tracer
#import pdb
#filepath = os.path.dirname(os.path.abspath(__file__))
f = open('wordsEn.txt')
first = {}
last = {}
while True:
word = f.readline()[:-2]
if word == '':
break
if len(word) > 2:
if word[:2] in first:
first[word[:2]].append(word)
else:
first[word[:2]] = [word]
if word[-2:] in last:
last[word[-2:]].append(word)
else:
last[word[-2:]] = [word]
start = raw_input('Startword: '), ''
end = raw_input('Goalword: ')
if start[0] == end:
print "Start = End"
else:
front = Queue.Queue()
front.put(start)
frontset = set([start[0]])
explored = {}
found = False
while not found:
if front.empty() == True:
print "No solution"
break
node = front.get()
frontset.remove(node[0])
explored[node[0]] = node[1]
if node[0][-2:] in first.keys():
for child in first[node[0][-2:]]:
if child not in explored.keys() and child not in frontset:
if child[-2:] == end[:2] or child[:2] == end[-2:]:
chain = [end, child, node[0]]
if node[0] == start[0]:
found = True
break
parent = node[1]
while parent != start[0]:
chain.append(parent)
parent = explored[parent]
chain.append(start[0])
found = True
break
frontset.add(child)
child = child, node[0]
front.put(child)
if node[0][:2] in last.keys() and not found:
for child in last[node[0][:2]]:
if child not in explored.keys() and child not in frontset:
if child[-2:] == end[:2] or child[:2] == end[-2:]:
chain = [end, child, node[0]]
if node[0] == start[0]:
found = True
break
parent = node[1]
while parent != start[0]:
chain.append(parent)
parent = explored[parent]
chain.append(start[0])
found = True
break
frontset.add(child)
child = child, node[0]
front.put(child)
if found:
break
print ''
print 'Found Chain:'
print ''
for i in reversed(chain):
print i
print ''