Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there's any odd/even numbers in an Iterable (e.g. list/tuple)?

Tags:

python

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?

like image 833
Charles Dong Avatar asked May 30 '17 07:05

Charles Dong


2 Answers

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
like image 137
Christian Dean Avatar answered Oct 04 '22 03:10

Christian Dean


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
like image 41
Azat Ibrakov Avatar answered Oct 04 '22 04:10

Azat Ibrakov