I want to create a function which will function like this:
def ceil(i: int, max: int) -> int:
return max if i > max else i
I am wondering if it is possible to do this without using conditions.
I think it should be possible to do the function with simple math. But I can't figure out how.
I don't want to use any built in functions.
CodePudding user response:
The following function will do the trick:
def ceil(i: int, max: int) -> int:
return min(i, max)
But at this point you don't event need the function! :)
ceil = min
and that's it.
P.S. I agree with the comment saying max is not a great name choice.
Based on the discussion from the comment section:
To avoid conditionals that min or abs builin functions have in Python you could do:
custom_abs = lambda v: v * ((v>0) - (v<0))
ceil = lambda a, b: (a b - custom_abs(a-b)) / 2
However, I still think you would have conditionals in CPython implementation due to type checking etc.
CodePudding user response:
So this is what I came up with - it is not pretty but it works.
def ceil(x, top=10): return (
1-1//(1 x))*(1-(
top-top//x
)//top)*x (
top-top//x
)//top*top
for i in range(1,21):
print(ceil(i))
