[英]My question is about a code i have described but it didn't work
SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). SUMMER OF '69:返回数组中数字的总和,除了忽略以 6 开头并延伸到下一个 9 的数字部分(每个 6 后面至少有一个 9)。 Return 0 for no numbers.¶
没有数字则返回 0。 ¶
I have tried to use the pop method but it didn't work.我曾尝试使用 pop 方法,但没有奏效。 I want to know why.
我想知道为什么。
def summer_69(arr):
num=(6,7,8,9)
if num not in arr:
return sum(arr)
if num in arr:
arr.pop(num)
return sum(arr)
print(summer_69([4,5,6,7,8,9]))
I am getting the whole sum like in this one I am getting like 39.我得到的总和就像我得到的 39 一样。
Pop removes the item at a specified index. Pop 删除指定索引处的项目。 Max index in your array is 5 (4 has index 0).
数组中的最大索引为 5(4 的索引为 0)。 I recommend finding the index of 6 via
我建议通过以下方式找到 6 的索引
arr.index(6)
Not efficient, but you can then repeatedly pop that index until it becomes 9, (and popping once more if "extending to" means including the 9).效率不高,但您可以重复弹出该索引,直到它变为 9,(如果“扩展到”意味着包括 9,则再次弹出)。
Instead of doing this i will suggest you to use a single loop as it will be more efficient.我会建议您使用单个循环而不是这样做,因为它会更有效。 Use single loop and keep adding number to sum until 6 is encountered.
使用单循环并不断将数字相加,直到遇到 6。 As soon as 6 comes skip the numbers till a 9 occurs.
一出现 6 就跳过数字,直到出现 9。 Again start to add numbers to sum.
再次开始将数字相加。 Runs in O(n).
在 O(n) 中运行。
i=0我=0
Sum =0总和 =0
While i < length:当我 < 长度:
If a[i] == 6:
While i < length and a[i] != 9:
i += 1
Else:
Sum += a[i]
i += 1
return Sum返回总和
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.