Skipping elements in a List Python

后端 未结 7 1650
隐瞒了意图╮
隐瞒了意图╮ 2021-01-17 13:28

I\'m new to programming and I\'m trying to do the codingbat.com problems to start. I came across this problem:

Given an array calculate the sum except when there is

7条回答
  •  -上瘾入骨i
    2021-01-17 14:08

    You can use the zip function to loop the values in pairs:

    def special_sum(numbers):
        s = 0
        for (prev, current) in zip([None] + numbers[:-1], numbers):
            if prev != 13 and current != 13:
                s += current
        return s
    

    or you can do a oneliner:

    def special_sum(numbers):
        return sum(current for (prev, current) in zip([None] + numbers[:-1], numbers)
                   if prev != 13 and current != 13)
    

    You can also use iterators:

    from itertools import izip, chain
    def special_sum(numbers):
        return sum(current for (prev, current) in izip(chain([None], numbers), numbers)
                   if prev != 13 and current != 13)
    

    (the first list in the izip is longer than the second, zip and izip ignore the extra values).

提交回复
热议问题