This is my solution to the codercharts problem http://codercharts.com/puzzle/word-swap but if keeps failing when I submit the solution because of the cpu_excess_time
. Please suggest possible optimisations for this problem, I believe my solution is correct but not optimal.
#!/usr/bin/python
def swap_words(first_word,second_word,word_dict):
wd = word_dict
#if the first word is equal to second ,
# we have got the target word
if first_word == second_word:
return [first_word]
for word in word_dict:
if len(word) == len(first_word) and \
sum([x != y for x,y in zip(list(first_word),list(word))]) == 1:
wd.remove(word)
ret = swap_words(word,second_word,wd)
if ret != False:
ret.append(first_word)
return ret
return False
if __name__ == '__main__':
import sys
filename = sys.argv[1]
first_word = sys.argv[2]
second_word = sys.argv[3]
text = open(filename).read()
word_dict = text.split('\n')
word_list = swap_words(first_word,second_word,word_dict)
for word in reversed(word_list):
print word