Suppose we're checking if there's any odd numbers in a list
. The most direct way is:
def has_odd(L):
for v in L:
if v % 2 == 1:
return True
return False
The has_odd
function checks if there's any odd numbers in a list
, once an odd number is found, it returns True
. But this seems a bit verbose. A more concise way using reduce
is as follow:
reduce(lambda res, v: res or bool(v), L, False)
But this will iterate through all elements and is unnecessary, because once an odd number is found the result is surely True
.
So, are there any other ways to do this?
You can use the any()
function to reduce the verbosity:
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> any(n % 2 == 1 for n in l)
True
>>>
Note however, any()
is pretty much the same as you had originally just generalized, so don't expect a speed improvement:
def any(iterable):
for element in iterable:
if element:
return True
return False
first of all let's write small indicator function for "oddness" like
def is_odd(number):
return number % 2
then we can write our indicator for "has at least one odd number" using any
with imap
/map
Python 2.*
from itertools import imap
def has_odd_number(iterable):
return any(imap(is_odd, iterable))
Python 3.*
def has_odd_number(iterable):
return any(map(is_odd, iterable))
or with generator expression
def has_odd_number(iterable):
return any(is_odd(number) for number in iterable)
Examples:
>>> has_odd_number([0])
False
>>> has_odd_number([1])
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With