-4

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.

mama
  • 2,046
  • 1
  • 7
  • 24

3 Answers3

2

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.

Lukasz Wiecek
  • 414
  • 2
  • 8
1

Code below works for -2**32 <= |a - b| <= 2**32 In this case, the sign bit of the integer is the 31st bit (counting from 0)

def ceil(a: int, b: int):
    return -a * ((a - b) >> 31) - b * ((b - a) >> 31)
Yuri Ginsburg
  • 2,302
  • 2
  • 13
  • 16
-1

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))
mama
  • 2,046
  • 1
  • 7
  • 24