使用 Python 查找数组乘积符号的程序
pythonserver side programmingprogramming更新于 2025/5/27 0:44:17
假设我们有一个名为 nums 的数组。我们必须找到数组中所有元素乘法结果的符号。
因此,如果输入为 nums = [-2,3,6,-9,2,-4],则输出将为负数,因为乘法结果为 -2592
为了解决这个问题,我们将遵循以下步骤 −
zeroes := 0,negatives := 0
对于 nums 中的每个 i,执行
如果 i 与 0 相同,则
zeroes := zeroes + 1
如果 i < 0,则
negatives := negatives + 1
如果零 > 0,则
返回"零"
否则,当负数 mod 2 与 0 相同时,则
返回 "Positive"
否则,
返回 "Negative"
让我们看看下面的实现以便更好地理解 −
示例
def solve(nums): zeroes,negatives = 0,0 for i in nums: if i == 0: zeroes+=1 if i < 0: negatives+=1 if zeroes > 0: return "Zero" elif negatives % 2 == 0: return "Positive" else: return "Negative" nums = [-2,3,6,-9,2,-4] print(solve(nums))
输入
[-2,3,6,-9,2,-4]
输出
Negative
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

