如何使用reduce而不使用lambda

时间:2017-05-21 05:38:16

标签: python lambda

初学者解决方案 - 工作

嗨伙计们。我成功编写了一些代码,如果全部都返回true 列表中的项目是素数。我认为这是一个很好的候选人 为"减少" - 到目前为止我只使用了reduce lambda - 是否可以避免使用lambda并使用直接函数

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

或者使用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)

从这里起作用

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]) 

错误讯息:

  

int参数必须是string或int not list

前一篇文章道歉 - 意外发送未完成

1 个答案:

答案 0 :(得分:2)

请使用布尔值TrueFalse,而不是字符串"True""False"。如果你使用布尔而不是字符串,以下是你的功能:

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

但这是不正确的,因为a不是数字而是之前的结果,所以它应该写成

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

但是我建议解除谓词和减速器并将其写成:

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

但是这种减少更好地写成:

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

然后可以删除地图:

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

我非常喜欢这种形式。

相关问题