Skipping elements in a List Python

后端 未结 7 1700
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 13:50

    I think this is the most compact solution:

    def triskaidekaphobicSum(sequence):
        return sum(sequence[i] for i in range(len(sequence))
                   if sequence[i] != 13 and (i == 0 or sequence[i-1] != 13))
    

    This uses the builtin sum() function on a generator expression. The generator produces all the elements in the sequence as long as they are not 13, or immediately following a 13. The extra "or" condition is to handle the first item in the sequence (which has no previous item).

提交回复
热议问题