如何通过我的代码制作伪代码**问题:**返回数组中数字的总和,对于空数组返回0。除非数字13非常不幸,所以它不计数,紧接在13之后的数字也不计数。
这是我的代码:
def sum13(nums):
while 13 in nums:
del(nums[ nums.index(13): nums.index(13)+2])
return (sum(nums))
您应该使用while
带有索引的循环,这样当遇到13项时,索引可以增加2而不是1:
def sum13(nums):
s = i = 0
while i < len(nums):
n = nums[i]
if n == 13:
i += 2
continue
s += n
i += 1
return s
以便:
sum13([2,4,13,5,2,1,13])
返回: 9
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句