Choose largest odd number python

Approach

Avoid using if-stmts to find maximum. Use python builtin max. Use either generator or filter to find only the odd numbers.

Using builtins like this is safer/more reliable because it is simpler to compose them, the code is well-tested, and the code executes mostly in C (rather than multiple byte code instructions).

Code

def find_largest_odd(*args):
    return max(arg for arg in args if arg & 1)

or:

def find_largest_odd(*args):
    return max(filter(lambda x: x & 1, args))

Test

>>> def find_largest_odd(*args):
...     return max(arg for arg in args if arg & 1)
... 
>>> print find_largest_odd(1, 3, 5, 7)
7
>>> print find_largest_odd(1, 2, 4, 6)
1

and:

>>> def find_largest_odd(*args):
...     return max(filter(lambda x: x & 1, args))
>>> print find_largest_odd(1, 3, 5, 7)
7
>>> print find_largest_odd(1, 2, 4, 6)
1

If you pass an empty sequence or provide only even numbers, you will get a ValueError:

>>> find_largest_odd(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in find_largest_odd
ValueError: max() arg is an empty sequence

References

Leave a Comment