我的代码中的“索引超出范围”在哪里?

时间:2019-07-19 17:12:01

标签: python-3.x

我正在尝试在数字13出现之前将所有数字加到数组中,如果没有,则将所有数字加到一个函数中。

productID
0  14306
1  60974
2  72961
3  78818
4  86765
5  155707
6  54405
7  69562

错误: def sum13(nums): a = 0 if len(nums) == 0: return 0 elif len(nums) == 1: if nums[0] == 13: return 0 return nums elif len(nums) >= 2: for i in range(len(nums)-1): if nums[a] == 13: a = a else: a += nums[i] return a

3 个答案:

答案 0 :(得分:0)

这可以写得更短,更简洁:

Parameter

答案 1 :(得分:0)

您不需要使用nums索引到a,只需使用in并在看到 13时中断即可:

def sum13(nums):
  total = 0
  for num in nums:
    if num == 13:
      break #  or return total
    total += num
  return total

答案 2 :(得分:0)

这是一个不使用break语句的解决方案,它说明数组中没有13,并在达到数字13时结束。

def sums13(nums):
    result = 0
    if(len(nums) ==0):
        return result
    else:
        for i in range(0,len(nums)):
            if(nums[i] == 13):
                return result
            else:
                result += nums[i]
    return result #This is the case where 13 is not in the array, but we have reached the end of the array.

或者,我们可以通过删除If / Else来启动函数,从而进一步简化此操作,因为如果数字列表为空,则for循环将不会运行。

def sums13(nums):
    result = 0
    for i in range(0,len(nums)):
        if(nums[i] == 13):
            return result
        else:
            result += nums[i]
    return result #This is the case where 13 is not in the array, but we have reached the end of the array. Also includes the array being empty.

通常将断言表示为不良做法,应尽量避免使用。这是根据您的要求的测试语句列表

>>> nums=[1,5,7,13,14,15]
>>> sums13(nums)
13
>>> nums=[1,2,3,4,5,6,7]
>>> sums13(nums)
28
>>> nums = []
>>> sums13(nums)
0
>>> nums=[13]
>>> sums13(nums)
0

我们还可以消除for循环的范围部分,并删除索引部分,以进一步简化操作!

def sums13(nums):
    result = 0
    for number in nums:
        if(number == 13):
            return result
        else:
            result += number
    return result #This is the case where 13 is not in the array, but we have reached the end

也许我可以看一下inline-if语句,但是也许...