2016-07-06 70 views
1

我正在做一個小項目,在這個項目中我的程序解開一個字符串並找到它的每個可能的組合。從另一個列表中尋找一個字符串對象

我有兩個列表; comboListwordListcomboList擁有這個詞的每個組合;例如,爲comboList'ABC'

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

(僅'CAB'是一個真正的字)

wordList持有56,000字從文本文件導入。這些都在英語詞典中找到並按長度排序,然後按字母順序排列。

isRealWord(comboList,wordList)是我的功能,通過檢查它是否在wordList中來測試comboList中哪些單詞是真實的。下面的代碼:

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' 

這是輸出:

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 
[] 

爲什麼if combo in wordList沒有返回True,如何解決?

+6

wordlist是否全部大寫呢? – L3viathan

+2

您可以使用>> print「{0}:{1}」替換您的isRealWord方法中的調試2行。format(combo,wordList)並查看究竟是什麼被比較 - 好的調試不錯 - wordList是一大堆字..但打印你的組合,看看它的檢查到底是什麼! – AK47

+0

附註:使用'set'來保存'wordList'會更快!如果您需要'wordList'作爲包含代碼的'list',那麼每次都可能在'isRealWord'裏面創建'set'。 – MisterMiyagi

回答

1

我認爲這裏的問題是,你比較兩個字符串相同的字母,但混合下/大案例
,看看我是否是正確的嘗試將所有的字轉換成wordList爲大寫,然後在isRealWord用大寫的字比較(只是要確定)如下:

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) 
+0

我認爲你需要將'wordList'參數改爲'UpperCaseWordList' –

+0

請注意,'wordList'現在是一個方法中的一個參數 - 所以我認爲調用將是這樣的:'isRealWord(comboList,UpperCaseWordList) –

2

我建議使用set,因爲它的實現會更快。有set.intersection方法。這裏是一個不區分大小寫的解決方案:

listOfActualWords = set.intersection(set(word.upper() for word in comboList), set(word.upper() for word in wordList)) 
相關問題