Uzair Ahmed
Uzair Ahmed

Reputation: 49

Look for a string object from a list in another list

I am doing a little project in which my program unscrambles a string and finds every possible combination of it.

I have two lists; comboList and wordList. comboList holds EVERY combination of the word; for example, the comboList for 'ABC' is:

['ABC','ACB','BAC','BCA','CAB','CBA']

(Only 'CAB' is a real word)

wordList holds about 56,000 words imported from a text file. These are all found in the English dictionary and sorted by length and then alphabetically.

isRealWord(comboList,wordList) is my function to test which words in comboList are real by checking if it is in the wordList. Here's the code:

def isRealWord(comboList, wordList):
    print 'Debug 1'
    for combo in comboList:
        print 'Debug 2'
        if combo in wordList:
           print 'Debug 3'
           print combo
           listOfActualWords.append(combo)
    print 'Debug 4'

This is the output:

run c:/Users/uzair/Documents/Programming/Python/unscramble.py
Please give a string of scrambled letters to unscramble: abc 
['A', 'B', 'C'] 
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] 
Loading word list... 
55909 words loaded 
Debug 1 
Debug 2 
Debug 2 
Debug 2 
Debug 2 
Debug 2 
Debug 2 
Debug 4 
[]

Why is if combo in wordList not returning True and how do I fix it?

Upvotes: 1

Views: 98

Answers (2)

Alex M
Alex M

Reputation: 2836

I'd suggest using set because it would be much faster due to its implementation. There is set.intersection method. Here is a case insensitive solution:

listOfActualWords = set.intersection(set(word.upper() for word in comboList), set(word.upper() for word in wordList))

Upvotes: 2

Gal Dreiman
Gal Dreiman

Reputation: 4009

I think the problem here is that you compare two strings with the same letters but with mixed lower/upper cases.
To see if i'm correct try to convert all word in wordList to upper-case and then in isRealWord compare with upper-case word (just to be sure) as follows:

UpperCaseWordList = [word.upper() for word in wordList]
...
def isRealWord(comboList, wordList):
    for combo.upper() in comboList:
        if combo in wordList:
           print combo
           listOfActualWords.append(combo)

Upvotes: 1

Related Questions