我试图理解导致这种情况的逻辑和过程,但仍然不明白为什么会这样。抱歉,如果这是一个非常简单/糟糕的问题。这是问题:返回数组中数字的总和,除了忽略以 6 开头并延伸到下一个 7 的数字部分(每个 6 后面至少有一个 7)。没有数字则返回 0。这是有错误的代码:def sum67(nums): ans = 0 if len(nums) == 0: return 0 elif 6 not in nums: for val in nums: ans += val return ans elif 6 in nums: x = nums.index(6) y = nums.index(7, x) for i in range(x, y): nums.pop(i) for val in nums: ans += val return ans这是错误:pop index out of range
1 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
哇哦!我刚刚了解了该del功能。
我的解决方案是更换:
elif 6 in nums:
x = nums.index(6)
y = nums.index(7, x)
for i in range(x, y):
nums.pop(i)`
和:
while 6 in nums:
x = nums.index(6)
y = nums.index(7, x)
del nums[x:y+1]
添加回答
举报
0/150
提交
取消
