Why do these two implementations produce different results?
I asked this question and got an excellent answer (thanks!). Part of the problem to be solved involved taking a word and de-interlacing it, so that you get two words, one containing the even-indexed characters of the original word, the other containing the odd-indexed characters.
The responder used the following code to do this:
for w in words:
even, odd = w[::2], w[1::2]
I did it this (worse) way:
for w in words:
lst1 = []
lst2 = []
for c in w:
if w.index(c) % 2 == 0:
lst1.append(c)
else:
lst2.append(c)
even = ''.join(lst1)
odd = ''.join(lst2)
Okay, my way is worse for a number of reasons. But it seems to me as though both ways should at least pro开发者_开发百科duce the same pairs of words. And yet, I get different results using his implementation than mine. Why is that?
Because index(c)
asks the index of the first occurrance of the letter in the word — so you are creating a single “bucket” for each letter. So if the first 'a'
is odd, then all of the 'a'
letters also get stuffed into the "odd" string. To fix this, you should just use enumerate()
to count:
for i, c in enumerate(word):
# check whether ``i`` is even/odd, etc
精彩评论