Skip to content

Instantly share code, notes, and snippets.

@Zenuncl
Last active December 27, 2015 23:48
Show Gist options
  • Save Zenuncl/7408281 to your computer and use it in GitHub Desktop.
Save Zenuncl/7408281 to your computer and use it in GitHub Desktop.
changeling
from WordLookup import lookup
# This is a helper function which converts a word string into a list with each letter as an element
def wordToList(word):
i=0
a=[]
while i < len(word):
a.append(word[i])
i+=1
return a
# This is a helper function which converts a list of letters into one word as a string
def ListToStr(Llist):
a=''
i=0
while i < len(Llist):
b=Llist[i]
i+=1
a=a+b
return a
# This helper function takes a word as parameter and returns the list of words that are only one letter different from the word
def oneLetterDiff(word):
letterlist=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
resultlist=[]
wordlist=wordToList(word)
for i in range (len(wordlist)):
for letter in letterlist:
if wordlist[i]!=letter:
newWord=wordlist
newWord[i]= letter
newWordstr=ListToStr(newWord)
wordlist=wordToList(word)
if lookup(newWordstr) != False:
resultlist.append(newWordstr)
return resultlist
# This is the main function which allows as to solve the changeling puzzle with a recursive function, the result gives a list from the starting word going through each steps to the final desired word
processList=[]
def changeling (start,end,steps):
global processList
processList.append (start)
if lookup (start) == False or lookup(end) == False:
return None
if start.islower()== False or end.islower()==False:
return None
if steps < 0:
return None
if len(start)!= len(end):
return None
if steps == 0 and start==end:
return end
elif steps == 0 and start !=end:
return None
else:
wordList=oneLetterDiff(start)
for n in wordList:
if n in processList:
continue
else:
start=n
changeling(start,end,steps-1)
return processList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment