1

When two integers are divided with the // integer operator, it returns the floor integer.

To have the ceil integer Only With Integer Operators (to avoid math.ceil), I wrote the following lambda function :

ceilint=lambda x, y: x//y+ (1 if x%y else 0)

It works, but I wonder (as I am a Python beginner), if it is the right way to do that (n.b. I am sure that operands are integers) or if a better solution exists.

Thanks for answer.

Amal K
  • 4,359
  • 2
  • 22
  • 44
Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • 3
    Does this answer your question? [Is there a ceiling equivalent of // operator in Python?](https://stackoverflow.com/questions/14822184/is-there-a-ceiling-equivalent-of-operator-in-python). The second answer does not use math.ceil – Tom McLean May 17 '21 at 15:30
  • Why do you want to avoid the `math.ceil` function though? – Konrad Rudolph May 17 '21 at 15:30
  • 1
    @TomMcLean. Thanks a lot. It is a better solution than mine. Problem solved – Stef1611 May 17 '21 at 15:33
  • @KonradRudolph. To avoid an import and to work only with integers – Stef1611 May 17 '21 at 15:34
  • @Stef1611 It’s part of the standard library. Avoiding such an import is ill-advised. *Do* take advantage of the standard library at every turn, don’t roll your own solutions unless there’s a specific reason to do so. – Konrad Rudolph May 17 '21 at 15:34
  • And the built in functions like sort and ceil might actually be faster than the code you write, because they are coded directly in C, which is much much faster... – Someone May 17 '21 at 15:35
  • @Someone. Are you sure ? `%timeit (10 + (3-1)) // 3` : 11.5 ns, `%timeit 10//3 + (1 if 10%3 else 0) `: 37.8 ns and `%timeit math.ceil(10/3) `: 264 ns. I use python 3.8.10 and jupyter notebook 6.3.0 – Stef1611 May 17 '21 at 15:42
  • math.ceil is slower because it uses floating point math over integer math. However the difference is negligable for most use cases – Tom McLean May 18 '21 at 13:31
  • It is slower in this senario because you are using only intergers and not floating point numbers, and also calling a function is slower than writing the code for it in the main file.....`%timeit 23 + 12` = `8.36 ns` but `def addit(x, y): return x + y %timeit addit(23, 12)` = `100 ns` – Someone May 19 '21 at 06:58

0 Answers0