Skipping elements in a List Python

后端 未结 7 1648
隐瞒了意图╮
隐瞒了意图╮ 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:55

    One tricky thing to notice is something like this: [1, 13, 13, 2, 3]

    You need to skip 2 too

    def getSum(l):
        sum = 0
        skip = False
        for i in l:
             if i == 13:
                 skip = True
                 continue
             if skip:
                 skip = False
                 continue
             sum += i
        return sum
    

    Explanation:

    You go through the items in the list one by one

    Each time you

    • First check if it's 13, if it is, then you mark skip as True, so that you can also skip next item.
    • Second, you check if skip is True, if it is, which means it's a item right after 13, so you need to skip this one too, and you also need to set skip back to False so that you don't skip next item.
    • Finally, if it's not either case above, you add the value up to sum

提交回复
热议问题