user7945450
user7945450

Reputation:

reduce without lambda

I succeeded in writing some code which returns true if all items in a list are prime numbers.
I think this is a good candidate for reduce - up to now I have only used reduce in conjunction with lambda - is it possible to avoid lambda and use a direct function?

def is_prime(list):
    np = "Prime"
    for n in list:
        if n < 2:
            np = "NonPrime"
            print np
            # return np
        else:
            for i in range(3, n):   #int(math.sqrt(n))
                if n % i == 0:
                    np ="NonPrime"
                    print np
    return np   

Upvotes: 1

Views: 596

Answers (1)

AChampion
AChampion

Reputation: 30258

You may want to refactor this code into checking if a number is prime and then using that to test if a list of numbers are all() prime. all() would be better than reduce() because it will short circuit.

Note: you shouldn't use list as a variable or argument as it hides the python builtin type.

def is_prime(n):
    if n < 2:
        return False
    for i in range(3, n):   #int(math.sqrt(n))
        if n % i == 0:
            return False
    return True

def all_primes(iterable):
    return all(is_prime(n) for n in iterable)

>>> all_primes([2,3,5,7])
True
>>> all_primes([2,3,5,8])
False

If you really wanted to implement this as reduce() then, you are effectively reducing a list of booleans to a single boolean using and, there is an operator for and defined in the operator module, operator.and_:

from functools import reduce   # Py3
import operator as op

def all_primes(iterable):
    return reduce(op.and_, (is_prime(n) for n in iterable))

Upvotes: 3

Related Questions