Hi, yesterday I threw together a little jumble solver that takes any anagram as an input and returns any real words that can be found using all of the letters of that anagram. Here is the code, it works fine when it comes to determining the answer, but I have a couple of questions.
# jumble.py
import string
def anagrams(s):
if s == "":
return [s]
else:
ans = []
for an in anagrams(s[1:]):
for pos in range(len(an)+1):
ans.append(an[:pos]+s[0]+an[pos:])
return ans
def dictionary(filename):
dict = {}
infile = open(filename, "r")
for line in infile:
word = line.split("\n")[0]
dict[word] = 1
infile.close()
return dict
def main():
anagram = raw_input("Please enter a word you need to unscramble: ")
anaLst = anagrams(anagram)
diction = dictionary("dictionary.txt")
for ana in anaLst:
if diction.has_key(ana):
print "The solution to the jumble is", ana
main()
My questions are:
1) Can anyone please explain to me why for some anagrams like ouhse (house) I only get the answer printed once while with other anagrams such as dunretnda (redundant) I get the answer printed multiple times (in this case, 4)?
2) Is there another way to write this code so I can solve much bigger anagrams without receiving a memory error or am I strictly locked down by the amount of ram I have on my computer? (*shakes fist at factorials* :p )
Thank you so much for your time and help.