ex11 利用异常解题

描述

  • 给定一个整数数组,返回它们的总和。
  • 如果整数数组中出现 13,那么每个 13 以及其后的 5 个数字(若有)都不计入总和。

示例

例1

  • 输入:[1, 2, 3]
  • 输出:6

例2

  • 输入:[1, 2, 13, 4, 5, 6, 7, 8, 9]
  • 输出:12

例3

  • 输入:[1, 2, 13, 4]
  • 输出:3

程序

def func(nums):
    i, t, s = 0, -6, 0  # index, temp, sum
    while i < len(nums):
        try:
            t = nums.index(13, t + 6)  # index -> valueError
            s += sum(nums[i:t])
            i = t + 6
        except ValueError:
            return s + sum(nums[i:])
    return s


# use pytest
def test_func():
    assert func([]) == 0
    assert func([1, 2, 3]) == 6
    assert func([1, 2, 13, 4, 5, 6, 7, 8, 9]) == 12
    assert func([1, 2, 13, 4]) == 3

知识点

>>> help(list.index)
Help on method_descriptor:

index(self, value, start=0, stop=9223372036854775807, /)
    Return first index of value.

    Raises ValueError if the value is not present.
posted @ 2019-12-18 20:05  YorkFish  阅读(253)  评论(0编辑  收藏  举报