简体   繁体   English

如何修复代码中的输出问题?

[英]How can I fix the output problem in my code?

So I wrote this code to print out true or false depending on whether the value goes below zero or not.所以我写了这段代码来根据值是否低于零来打印 true 或 false。 Here is my code这是我的代码

    L = [10,10,10]
init_hp = 0
def is_dead(L: list[int], init_hp:int):
    if init_hp == 0:
        return True
    elif sum(L) + init_hp > 0:
        return False
    else:
        return True
print(is_dead(L,init_hp))

However, for the L: list I want to make sure that the output prints out True if the value has gone below zero already.但是,对于L: list ,如果值已经低于零,我想确保输出打印出 True 。 For example, if L: list = [2,-3,5] , I want to make sure that the output prints out True , because 2+(-3), the first two variables, already return a negative number,"-1", EVEN THOUGH THE END RESULT IS POSITIVE... however using my code, that doesn't work, what code should I use to make sure that it will print true if a scenario like this happens例如,如果L: list = [2,-3,5] ,我想确保输出打印出True ,因为前两个变量 2+(-3) 已经返回一个负数,"- 1",即使最终结果是肯定的......但是使用我的代码,这不起作用,如果发生这样的情况,我应该使用什么代码来确保它会打印为真

You can use loop and iterate all numbers in the list.您可以使用循环并迭代列表中的所有数字。

L = [10, 10, 10]
init_hp = 0
def is_dead(L: list[int], init_hp:int):
    if init_hp == 0:
        return True
    v = 0
    for num in L:
        if v+num < 0:
            return True
        v += num
    
    if init_hp+v < 0:
         return True
    return False

print(is_dead(L,init_hp))

The shortest way I could think of was to use itertools.accumulate :我能想到的最短方法是使用itertools.accumulate

from typing import List
from itertools import accumulate


def is_dead(lst: List[int], i_hp: int):
    if i_hp == 0:
        return True
    for total in accumulate(lst):
        if total < 0:
            return True
    return False


print(is_dead([2, -3, 5], 1))
# True
print(is_dead([10, 10, 10], 1))
# False

Or slightly shorter (but also may be slightly less memory efficient):或稍短(但也可能内存效率稍低):

def is_dead(lst: List[int], i_hp: int):
    if i_hp == 0:
        return True
    if [True for total in accumulate(lst) if total < 0]:
        return True
    return False

Sources:资料来源:

You can use a for loop to iterate through the numbers and check whether the sum is less than zero or not.您可以使用 for 循环遍历数字并检查总和是否小于零。

def is_dead(L: list[int], init_hp: int):
    if init_hp <= 0:
        return True

    s = 0
    for num in L:
        s += num
        if s < 0:
            return True

    return False  # sum > 0


# Test cases:
print(is_dead([2, -3, 5], 1))  # True
print(is_dead([10, 10, 10], -1))  # True
print(is_dead([10, 10, 10], 1))  # False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM