您可以迭代地切出 6 和 9 之间的部分,直到没有更多对,然后对余数调用 sum。
对于“切片”,我们使用 Python 的索引切片,它通过给出开始索引和结束索引(不包括在内)来工作。
>>> [0, 1, 2, 3][1:3] == [1, 2]
True
>>> [0, 1, 2, 3][1:]
[1, 2, 3]
>>> [0, 1, 2, 3][:2]
[0, 1]
我们用list.index 找到前 6 个和后 9 个的位置。我们必须确保只在 6 之后才开始寻找 9。这给出了
def number_69(arr):
while 6 in arr:
index = arr.index(6)
arr = arr[:index] + arr[index + arr[index:].index(9) + 1:]
# +index because we are removing it from arr[index:]
# +1 because we don't want to include the 9 in the new list
return sum(arr)
由于我们知道每个 6 后面都会跟着一个 9,所以没有必要检查列表中是否有 9。因此,此函数将删除所有6-9 块,然后才返回整个列表的总和。
如果 6 没有伴随的 9,则此函数将引发 ValueError。这可以通过检查 9 来解决,但这必须在前 6 的索引之后完成。如果没有找到 9,我们还必须将 break 退出循环,因为 6 不会被删除.
def number_69(arr):
while 6 in arr:
index = arr.index(6)
if 9 in arr[index:]:
arr = arr[:index] + arr[index + arr[index:].index(9) + 1:]
# +index because we are removing it from arr[index:]
# +1 because we don't want to include the 9 in the new list
else:
break
return sum(arr)