在使用C++之后如何用Python思考?

Jos*_*osh 7 c++ python

我是Python的新手,并试图通过将以下C++函数复制到python中来学习它

// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
void equivalentWords(vector <string> words, ofstream & outFile) {
    outFile << "Equivalent words\n";

    // checkedWord is parallel to the words vector. It is
    // used to make sure each word is only displayed once.
    vector <bool> checkedWord (words.size(), false);

    for(int i = 0; i < words.size(); i++) {
        if (!checkedWord[i]){
            outFile << "  ";
            for(int j = i; j < words.size(); j++){
                if(equivalentWords(words[i], words[j], outFile)) {
                    outFile << words[j] << " ";
                    checkedWord[j] = true;
                }
            }
            outFile << "\n";    
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的python代码(下面),而不是第二个向量,我有一个字符串列表的列表("单词"),前一个字符串中的字符的排序列表(因为字符串是不可变的),和一个布尔(告诉我们这个词是否已被检查过).但是,我无法弄清楚如何在遍历列表时更改值.

    for word, s_word, checked in words:
    if not checked:
        for word1, s_word1, checked1 in words:
            if s_word1 == s_word:
                checked1 = True # this doesn't work
                print word1,
        print ""
Run Code Online (Sandbox Code Playgroud)

任何有关这样做或更多思考"Pythony"的帮助表示赞赏.

cat*_*try 5

保持简单,这是O(N)的复杂性,如果你没有GB的数据,那就足够了.请注意,set()并且dict()基本上是散列索引(free和builtin!).

index = {}
for word, s_word in words:
    index[s_word] = index.get(s_word, []) + [word]

for similar_words in index.values():
    print ' '.join(similar_words)        
Run Code Online (Sandbox Code Playgroud)

不知道你使用它是什么,但你可能会感兴趣的是在python 2.7 中,在collections模块中引入了Counter类.

如果你真的想保留你的算法并更新一个布尔列表(你没有,因为那个算法会做低效的双循环),你会这样做:

checked = [False] * len(words)
for i, (word, word_s) in enumerate(words):
    if checked[i]:
       continue
    for j, (other, other_s) in enumerate(words[i:]):
        if word_s == other_s:
            print other,
            checked[i+j] = True
    print
Run Code Online (Sandbox Code Playgroud)