如何在Python中将负数更改为零而不使用决策结构

问题描述 投票:0回答:4

我有一个程序可以确定您在某次活动中每天获得的积分数,持续 5 天。

源代码:

total=0

for x in range (5):
    points=int(input('How many points did you get today?'))
    total=total+points

print ('You got {0} points this event'.format(total))

我的问题是如何在不使用决策语句的情况下使任何数字低于或等于零 a 0 (if、case,我认为 while 或 for 循环也是不允许的)

algorithm python-3.x validation negative-number
4个回答
172
投票

可以使用内置函数吗?因为这通常是使用以下方法完成的:

max(0, points)

23
投票
>>> f=lambda a: (abs(a)+a)/2         
>>> f(a)
0
>>> f(3)
3
>>> f(-3)
0
>>> f(0)
0

4
投票

由于我没有将布尔运算符视为限制,因此您可以使用:

points * (points>0)

0
投票

这是一种通过 bitbashing 来实现的方法,避免乘法:

def zerolimit(n: int) -> int:
    """normalize 'n' so that
        n = 0 when n < 0, else
        n = n
        """
    return n & ((n < 0) - 1)
© www.soinside.com 2019 - 2024. All rights reserved.