我有一个程序可以确定您在某次活动中每天获得的积分数,持续 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 循环也是不允许的)
可以使用内置函数吗?因为这通常是使用以下方法完成的:
max(0, points)
>>> f=lambda a: (abs(a)+a)/2
>>> f(a)
0
>>> f(3)
3
>>> f(-3)
0
>>> f(0)
0
由于我没有将布尔运算符视为限制,因此您可以使用:
points * (points>0)
这是一种通过 bitbashing 来实现的方法,避免乘法:
def zerolimit(n: int) -> int:
"""normalize 'n' so that
n = 0 when n < 0, else
n = n
"""
return n & ((n < 0) - 1)