kdlayton
kdlayton

Reputation: 31

Adding numbers in a list except a specific number and the following number

I am new to programming and I am trying to add up all the numbers in a given list except for the the number 13 and any number following the number 13. the problem that I am having is that if 13 is on the end of the list it won't add the first number. Any help would be appreciated. The code I have is as follows:

def sum13(nums):
    total = 0
    for i in range(len(nums)):
        if nums[i] == 13 or nums[i-1] == 13:
            total += 0
        else:
            total += nums[i]

    return total

def main():
    print sum13([1, 2, 2, 1, 13])
    print sum13([1, 2, 13, 2, 1, 13])
main()

The two examples should result in 6 and 4 however it results in 5 and 3 because it isn't adding the 1 at the beginning.

Upvotes: 3

Views: 485

Answers (2)

remy
remy

Reputation: 4743

My proposition:

def sum13(numbers):
    total = 0
    skip = False
    for i, number in enumerate(numbers):
        if number == 13:
            skip = True
            continue
        if skip:
            skip = False
            continue
        total += number

    return total


def test():
    cases = [
        ([13, 1, 1], 1),
        ([13, 1, 5, 13], 5),
        ([1, 13, 5, 1], 2),
        ([1, 2, 2, 1, 13], 6),
        ([1, 2, 13, 2, 1, 13], 4),
    ]
    for case in cases:
        assert sum13(case[0]) == case[1]


test()

Read about enumerate if it's new for you: https://docs.python.org/3.4/library/functions.html#enumerate

Upvotes: 0

Karin
Karin

Reputation: 8600

In Python, an index of -1 means the last item in a list. So, in your code, when i is 0 (the first number), it will not count it because the last item in the list is 13.

You can fix this with a simple check that i > 1 on that condition:

if nums[i] == 13 or (i > 0 and nums[i - 1] == 13):

Also for what it's worth, because we all love one-liners, here's an equivalent function in a line:

return sum(num for i, num in enumerate(nums) if num != 13 and (i == 0 or nums[i - 1] != 13))

Upvotes: 2

Related Questions