简体   繁体   English

我的问题是关于我描述的代码但它不起作用

[英]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.

相关问题 学习编码,我有一个关于 IF on python 的问题 - Learning to code, I have a question about IF on python 如何编写这个 python 代码。 我试过但没有用 - How to write this python code. I have tried it but didn't work 想知道为什么我的代码无法删除我想要的任何数字? - wondering why my code didn't work for deleting any number I wanted? 我有 pip 安装了 pydub 但仍然没有工作 - I have pip installed pydub but still didn't work 我对这个 Python 代码背后的逻辑有一个简单的问题 - I have a simple question about the logic behind this Python code 关于为什么结果没有更新的问题? - Question about why didn't the result get updated? 如何修改我的代码以正确打印所描述的模式? - How can i modify my code to correctly print the pattern described? 我怎样才能让我的模型以 2 张量作为输入。 我试过使用合并层,但我并没有完全让它工作 - How can i make my model take 2 tensors as inputs. I have tried using a merge layer, but i didn't quite get it to work predict 方法的参数必须采用什么格式? 我的 x_training 中的数据是列表,所以我不知道为什么列表不起作用 - In what format does the argument to the predict method have to be in? The data in my x_training are lists so I don't why list didn't work 关于我返回最长单词的代码的问题 - Question about my code for returning longest word
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM