user7945450
user7945450

Reputation:

How to use reduce without lambda

Beginners solution - works

Hi folks. 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 direct function

def is_prime(list):
    np = "Prime"
    for n in list:
        if n < 2:
            np = "NonPrime"
            print np
        else:
            for i in range(3, n):
                if n % i == 0:
                    np ="NonPrime"
                    print np
    return np
x = is_prime([3,5,13])
print x

alternatively using reduce

def is_prime_no(x):  #"True" represents Prime
    np = "True"
    if x < 2:
        np = "False"
    else:
        for i in range(3, x):   #int(math.sqrt(n))
            if x % i == 0:
                np ="False"
    return np

print is_prime_no(12)

def prime_check(a,b):
    if is_prime_no(a) == "True" and is_prime_no(b) == "True":
        return "True"
    else:
        return "False"

print "prime check result ", prime_check(13,17)

From here does not work

values = [13,17,2,19]
def list_prime_check(values):
    return reduce(prime_check, int(values))
print "Checking that all items in list are prime ", list_prime_check([0, 37, 40, 100]) 

Error message:

int argument must be string or int not list

apologies for previous post - accidently sent without being completed

Upvotes: 1

Views: 1251

Answers (1)

Dan D.
Dan D.

Reputation: 74645

Please use the Booleans True and False and not the strings "True" and "False". The following is your function if you were to use Booleans rather than strings:

def prime_check(a,b):
    return is_prime_no(a) and is_prime_no(b)

But this would be incorrect as a is not a number but rather the previous result so it should be written as

def prime_check(a,b):
    return a and is_prime_no(b)

But I would suggest lifting the predicate and the reducer out and writing it as:

from operator import and_
def list_prime_check(values):
    return reduce(and_, map(is_prime_no, map(int, values)))

But that reduce is better written as:

    return all(map(is_prime_no, map(int, values)))

And then the maps could be removed:

    return all(is_prime_no(int(v)) for v in values)

Which is the form of this which I greatly prefer.

Upvotes: 3

Related Questions