所以我寫了這段代碼來根據值是否低于零來列印 true 或 false。這是我的代碼
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))
但是,對于L: list我想確保如果值已經低于零,則輸出會列印出 True 。例如,如果L: list = [2,-3,5],我想確保輸出列印出來True,因為前兩個變數 2 (-3) 已經回傳負數“-1”,即使最終結果是正數...但是使用我的代碼,這不起作用,如果發生這樣的情況,我應該使用什么代碼來確保它會列印真
uj5u.com熱心網友回復:
我能想到的最短方法是使用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
或稍短(但也可能記憶體效率稍低):
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
資料來源:
itertools.accumulate檔案
uj5u.com熱心網友回復:
您可以使用回圈并迭代串列中的所有數字。
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))
uj5u.com熱心網友回復:
您可以使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328986.html
上一篇:需要按特定順序從串列中獲取索引
