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:
				break
			print word

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

Recommended Answers

All 3 Replies

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)
scrambled_list.sort()

for word in words_in:
    word_list = list(word.strip().lower())
    word_list.sort()
    ## 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

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.