Skipping elements in a List Python

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

    Use a while loop to walk through the list, incrementing i manually. On each iteration, if you encounter a 13, increment i twice; otherwise, add the value to a running sum and increment i once.

    def skip13s(l):
        i = 0
        s = 0
        while (i < len(l)):
            if l[i] == 13:
                i += 1
            else:
                s += l[i]
            i += 1
        return s
    

提交回复
热议问题