-5
def is_odd(num):
    # Return True or False, depending on if the input number is odd. 
    # Odd numbers are 1, 3, 5, 7, and so on. 
    # Even numbers are 0, 2, 4, 6, and so on. 

我想知道你会怎么做才能得到这些答案。

4

2 回答 2

29
def is_odd(num):
    return num & 0x1

它不是最易读的,但它很快:

In [11]: %timeit is_odd(123443112344312)
10000000 loops, best of 3: 164 ns per loop

相对

def is_odd2(num):
   return num % 2 != 0

In [10]: %timeit is_odd2(123443112344312)
1000000 loops, best of 3: 267 ns per loop

或者,使返回值与is_odd

def is_odd3(num):
   return num % 2

In [21]: %timeit is_odd3(123443112344312)
1000000 loops, best of 3: 205 ns per loop
于 2013-02-01T16:46:50.673 回答
8
def is_odd(num):
   return num % 2 != 0

符号“%”被称为模并返回一个数字除以另一个数字的余数。

于 2013-02-01T16:45:21.337 回答