- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWordLadder.py
More file actions
Latest commit
89 lines (76 loc) · 2.03 KB
/
Copy pathWordLadder.py
File metadata and controls
89 lines (76 loc) · 2.03 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
77
78
79
80
81
82
83
84
85
86
87
88
89
'''
word ladder
only change one letter every time
return the minimum steps
'''
DICT= ['cat','cot','dot','dog']
CHARS= ['a','b','c','d','e','g','t','o']
defget_one_letter_neighbors(word):
# make words that are one letter changed from the given word
char_list= [cforcinword]
# print char_list
length=len(char_list)
neighbors= []
foriinrange(length):
forcharinCHARS:
ifchar!=char_list[i]:
printchar
new_word_list=char_list[:]
new_word_list[i] =char
new_word=''.join(new_word_list)
ifnew_wordinDICT:
printnew_word
neighbors.append(new_word)
returnneighbors
defword_ladder(word1,word2):
'''
bfs searching for the minimus steps between two words
'''
# queue = []
# neighbors = get_one_letter_neighbors(word1)
# for new_word in neighbors:
# new_neighbors = get_one_letter_neighbors(new_word)
# if new_neighbors:
# queue.append(new_word)
queue= []
queue.append([word1])
whilequeue:
# ['cat']
path=queue.pop(0)
ifpath[-1] ==word2:
returnpath
# ['cot', 'bat', 'mat']
children=get_one_letter_neighbors(path[-1])
# ['cat', ['cot', 'bat', 'mat']]
queue.append(path[:] + [children])
returnNone
defbfs(initial_state, finish_state, get_child_states):
queue= []
queue.append(initial_state)
whilequeue:
state=queue.pop(0)
ifstate==finish_state:
returnTrue
queue.extend(get_child_states(state))
returnFalse
defbfs_path(initial_state, finish_state, get_child_states):
queue= []
# ['cat']
queue.append([initial_state])
whilequeue:
# ['cat', 'cot']
path=queue.pop(0)
# 'cot'
ifpath[-1] ==finish_state:
returnpath
forchildinget_child_states(path[-1]):
# 'cot' -> ['cat', 'cot']
# 'bat' -> ['cat', 'bat']
# 'mat' -> ['cat', 'mat']
new_path=path[:]
new_path.append(child)
queue.append(new_path)
returnNone
word1='cat'
word2='dog'
printword_ladder(word1,word2)