python - 如何在没有lambda的情况下使用reduce

标签 python lambda

初学者解决方案 - 有效

大家好。我成功地编写了一些代码,如果全部返回 true 列表中的项目是素数。我认为这是一个很好的候选人 对于“reduce” - 到目前为止我只将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

打印 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 argument must be string or int not list

对之前的帖子表示歉意 - 意外发送而未完成

最佳答案

请使用 bool 值 TrueFalse,而不是字符串 "True""False"。如果您要使用 bool 值而不是字符串,则以下是您的函数:

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

但是这个reduce最好写成:

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

然后可以删除 map :

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

这是我非常喜欢的形式。

关于python - 如何在没有lambda的情况下使用reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093559/

相关文章:

c# - 具有泛型类属性的 LINQ 表达式

python - 使用元组作为 lambda 的参数会引发有关缺少所需位置参数的错误

python - Quandl + Python : The date column not "working"

Python Regex 匹配文件列表中的文件(出错)

Python 和 Tkinter - 设置标签文本变量的按钮命令问题

C++:具有 `std::lock_guard` 的互斥量是否足以同步两个 `std::thread`?

AWS Lambda 中通过 Cloud9 的 Python 3rd 方模块

python - 如何转义特殊字符并在命令提示符下运行命令?

python - 获取numpy中多维切片沿特定轴的索引

python - Django South - 如何重置迁移历史记录并在 Django 应用程序上开始清理