I just wanted to know that is there a way of implementing ceil function without using if-else?
With if-else (for a/b)
it can be implemented as:
if a%b == 0:
return(a/b)
else:
return(a//b + 1)
最简单的是。
a//b + bool(a%b)
而只是为了安全,
b and (a//b + bool(a%b))
干杯。
如果它们是整数,这样应该可以工作(我猜你有一个有理数表示):
a/b + (a%b!=0)
否则,请替换a/b
为int(a/b)
,或者更好,如下所示a//b
。
-(-a//b)
Perhaps the simplest?
========================
*Edited per @Gilles's comment:
for an integer n,
floor(x)=n for x in [n, n+1)
ceil(y)=n+1 for y in (n, n+1]
So, floor(-y)=-n-1 for -y in [-n-1, -n)
,
and ceil(y)=-floor(-y)=n+1 for y in (n, n+1]
In Python, floor(a/b) = a//b
.
Thus ceil(a/b) = -(-a//b)