python - 将连续整数列表的每个可能子集中的整数相乘

标签 python python-3.x primes

我有以下整数列表:

prime_factors = [2,3,5,7,11,13,17,19,23]

将连续整数的每个子集的元素相乘的有效方法是什么?

为了进一步说明,我需要输出包括以下乘法的结果:2*33*52*3* 5, 13*17*19, 7*11*13*17*19, 2*3*5*7*11*13 *17*19*23 和所有其他可能的连续素数组合。输出不应包括 2*55*7*13 等。

最佳答案

您可以使用 itertools.accumulate 执行此操作.

from itertools import accumulate
from operator import mul

def consec_mult(data):
    for i in range(len(data) - 1):
        it = accumulate(data[i:], mul)
        # Skip the single item
        next(it)
        yield from it

# Test

prime_factors = [2, 3, 5, 7, 11]
print(*consec_mult(prime_factors))

输出

6 30 210 2310 15 105 1155 35 385 77

或者如果您希望结果按数字顺序排序:

print(*sorted(consec_mult(prime_factors)))

输出

6 15 30 35 77 105 210 385 1155 2310

关于python - 将连续整数列表的每个可能子集中的整数相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010930/

相关文章:

Python pandas 使用滚动以矢量化方式应用于 groupby 对象来计算机车车辆 beta

python - 在 Mac 终端上的 doctest 中运行 +NORMALIZE WHITESPACE 时出错

python-3.x - 为什么python选择器模块没有套接字错误事件

python-3.x - 如果初始条件触发终端 = True 的事件,Solve_ivp 集成将卡住

python - 与 "optimized"迭代素数搜索相比,为什么埃拉托色尼筛法这么慢? ( python 3)

c - 这个 isPrime 函数是如何工作的?

python - 关键字参数

python - 安装 discord.py 1.0 时遇到问题

python - isinstance() 和 issubclass() 返回冲突的结果

python - 为什么我的素数检查代码没有显示正确的输出?