在C中工作后如何用Python思考?

前端之家收集整理的这篇文章主要介绍了在C中工作后如何用Python思考?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Python的新手,并试图通过将以下C函数复制到python中来学习它
  1. // determines which words in a vector consist of the same letters
  2. // outputs the words with the same letters on the same line
  3. void equivalentWords(vector <string> words,ofstream & outFile) {
  4. outFile << "Equivalent words\n";
  5.  
  6. // checkedWord is parallel to the words vector. It is
  7. // used to make sure each word is only displayed once.
  8. vector <bool> checkedWord (words.size(),false);
  9.  
  10. for(int i = 0; i < words.size(); i++) {
  11. if (!checkedWord[i]){
  12. outFile << " ";
  13. for(int j = i; j < words.size(); j++){
  14. if(equivalentWords(words[i],words[j],outFile)) {
  15. outFile << words[j] << " ";
  16. checkedWord[j] = true;
  17. }
  18. }
  19. outFile << "\n";
  20. }
  21. }
  22. }

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

  1. for word,s_word,checked in words:
  2. if not checked:
  3. for word1,s_word1,checked1 in words:
  4. if s_word1 == s_word:
  5. checked1 = True # this doesn't work
  6. print word1,print ""

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

解决方法

保持简单,这是O(N)的复杂性,如果你没有GB的数据,那就足够了.请注意,set()和dict()基本上是一个散列索引(free和builtin!).
  1. index = {}
  2. for word,s_word in words:
  3. index[s_word] = index.get(s_word,[]) + [word]
  4.  
  5. for similar_words in index.values():
  6. print ' '.join(similar_words)

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

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

  1. checked = [False] * len(words)
  2. for i,(word,word_s) in enumerate(words):
  3. if checked[i]:
  4. continue
  5. for j,(other,other_s) in enumerate(words[i:]):
  6. if word_s == other_s:
  7. print other,checked[i+j] = True
  8. print

猜你在找的C&C++相关文章