Is & faster than % when checking for odd numbers?

前端 未结 8 944
鱼传尺愫
鱼传尺愫 2020-11-30 04:13

To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?

>>> def isodd(num):
        return num & 1 a         


        
8条回答
  •  情话喂你
    2020-11-30 04:43

    Apart from the evil optimization, it takes away the very idiomatic "var % 2 == 0" that every coder understands without looking twice. So this is violates pythons zen as well for very little gain.

    Furthermore a = b and True or False has been superseded for better readability by

    return True if num & 1 else False

提交回复
热议问题