开发者

Truncating division in Python 3.2

开发者 https://www.devze.com 2023-02-20 16:32 出处:网络
Is开发者_如何学Go integer floor division // faster than float division / in Python 3.2? If I know I\'m going to be working with integers only, should I favour // instead of defaulting to /?
  1. Is开发者_如何学Go integer floor division // faster than float division / in Python 3.2? If I know I'm going to be working with integers only, should I favour // instead of defaulting to /?

  2. How do I get integer truncation behaviour in Python 3.2?

    1/2 = 0

    -1/2 = 0

Thanks.


from math import (floor, ceil)
def trunc_div(a, b):
    c = a / b
    return floor(c) if c > 0 else ceil(c)

Test it to make sure it's right. It's late and I'm doing math while sleepy.

Actually, don't do that. While seeing if I could subclass int to do truncated division (don't do that either (also, it didn't work)), it occurred to me that int() itself will truncate reals, resulting in this:

def trunc_div(a, b):
    return int(a / b)

Which is a rather foolish wrapper.

So, just use float division, and truncate it with int():

>>> int(1 / 2)
0
>>> int(-1 / 2)
0

This gets you pretty close to the infix notation you desired.

The moral of this story is... don't let your friends code while drowsy.

0

精彩评论

暂无评论...
验证码 换一张
取 消