Help thinking "Pythony"
Posted
by Josh
on Stack Overflow
See other posts from Stack Overflow
or by Josh
Published on 2010-05-21T01:30:18Z
Indexed on
2010/05/21
1:40 UTC
Read the original article
Hit count: 249
I'm brand new to Python and trying to learn it by replicating the following C++ function into 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";
}
}
}
In my python code (below), rather than having a second vector, I have a list ("words") of lists of a string, a sorted list of the chars in the former string (because strings are immutable), and a bool (that tells if the word has been checked yet). However, I can't figure out how to change a value as you iterate through a list.
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 ""
Any help on doing this or thinking more "Pythony" is appreciated.
© Stack Overflow or respective owner