Home > OS >  How can I fix the output problem in my code?
How can I fix the output problem in my code?

Time:10-21

So I wrote this code to print out true or false depending on whether the value goes below zero or not. 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. 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

CodePudding user response:

The shortest way I could think of was to use 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:

CodePudding user response:

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))

CodePudding user response:

You can use a for loop to iterate through the numbers and check whether the sum is less than zero or not.

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
  • Related