My daughter plays FaceBook games and is always asking me to solve anagrams. So I thought I would make a script for her to enter a scrambled word and it would compare it to the built-in spell check dictionary. But this code returns words such as quip and quiz when I enter 'quit' as a test word. What am I doing wrong?

infile = open ("/usr/share/dict/american-english", "r")
dict = infile.readlines()

scrambled = raw_input("Enter the scrambled word: ")

for word in dict:
	word = word.strip()
	if len(word) == len(scrambled):
		for letter in scrambled:
			if letter not in word:
			print word

infile is the path to your on-board spell-checking dict.

6 Years
Discussion Span
Last Post by txwooley

You should sort both words and compare. Your code will compare "a" to "aa" and find them equal. Note that any anagram program will take "odg" and return "god" and "dog" which is all it can do.

infile = open ("/usr/share/dict/american-english", "r")
## "dict" is a reserved word
words_in = infile.readlines()
scrambled = raw_input("Enter the scrambled word: ")
scrambled = scrambled.lower()
scrambled_list = list(scrambled)

for word in words_in:
    word_list = list(word.strip().lower())
    ## you don't really have to compare lengths when using lists as the
    ## extra compare takes about as long as finding the first difference
    if word_list == scrambled_list:
        print word, scrambled

Edited by woooee: n/a


See code snippets for my anagram word finders, if you only need results and not want to spend time reinventing the wheel.

Wooeee's code looks correct also, take your pick.

Edited by pyTony: n/a


That did the trick. Thanks to both of you. When I sat down to do this, it seemed a lot simpler than when I actually started typing.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.