What do you want to do if there is no solution?
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
I took your code and changed it mildly to give you an idea how to proceed ...
# unscramble a line of words
def permutation(s):
if s == "":
return [s]
else:
ans = []
for an in permutation(s[1:]):
for pos in range(len(an)+1):
ans.append(an[:pos]+s[0]+an[pos:])
return ans
def dictionary(wordlist):
dict = {}
infile = open(wordlist, "r")
for line in infile:
word = line.split("\n")[0]
# all words in lower case!!!
word = word.lower()
dict[word] = 1
infile.close()
return dict
def main():
diction = dictionary("wordlist.txt")
# enter all the words that fit on a line or limit the number
anagram = raw_input("Please enter space separated words you need to unscramble: ")
wordLst = anagram.split(None)
for word in wordLst:
anaLst = permutation(word)
for ana in anaLst:
if diction.has_key(ana):
diction[ana] = word
#print "The solution to the jumble is" , ana
solutionLst = []
for k, v in diction.iteritems():
if v != 1:
solutionLst.append(k)
print "%s unscrambled = %s" % (v, k)
print solutionLst
main()
You could limit the scrambled words entered with a loop.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
I liked your recursive anagram creator, but it is expensive because it generates n! strings for a size n scramble. I tested it with
print anagrams("Hi There")
and my reasonably fast machine cried and locked up. :lol:
Another possibility would be to test whether your scramble is an anagram for each word in the list. You could do this by seeing whether each letter in the scramble is somewhere in the word, removing that letter from the word if found. Here's the idea:
def isanagram(source, target):
"""returns True if source is an anagram of target, False
otherwise."""
# speed-up if your dictionary is large:
# if len(source) != len(target): return False
for i in source:
pos = target.find(i)
if pos == -1:
return False
else:
# remove found letter from the target (non-destructively)
target = target[:pos]+target[pos+1:]
return True
In the worst case, this runs O(n^2 * length of dictionary), but with much better performance on average. I found a noticeable speed-up just on this: print isanagram("Hi There", "There Hi")
hope it helps,
Jeff Cagle
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156