开发者

Why do these two implementations produce different results?

开发者 https://www.devze.com 2023-02-21 19:58 出处:网络
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 ch

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
0

精彩评论

暂无评论...
验证码 换一张
取 消