python - 简化 Python 迭代

标签 python product factorization

每次我尝试解决一些数学问题,例如找到特定数量因子的特定乘积时,我都会在 Python 中执行此操作

for x in xrange(1,10):
    for y in xrange(1,10):
        for z in xrange(1,10):
           product = x * y * z
           if product == 36:
               print "factors : {0},{1},{2}".format(x,y,z)

在这个例子中,它非常简单,可以快速完成工作,但我想知道你们是否知道一种更简单或更简单的方法来编写它。关于如何在不使用那么多迭代或一遍又一遍地重复几乎相同的代码的情况下执行此操作的任何想法。这些显然是针对 3 个因素,但我添加的因素越多,代码就越长、重复得越多。关于如何简化这种简单类型问题的代码的任何想法? 谢谢

最佳答案

Itertool 的 cartesian product模拟多个嵌套for循环的效果。

import itertools

for x, y, z in itertools.product(range(1,10), range(1,10), range(1,10)):
    product = x * y * z
    if product == 36:
        print "factors : {0},{1},{2}".format(x,y,z)

结果:

factors : 1,4,9
factors : 1,6,6
factors : 1,9,4
(...etc)

如果每个 x、y 和 z 的范围始终相同,您可以只指定一次:

for x, y, z in itertools.product(range(1,10), repeat=3):

如果您厌倦了在 product = 行中输入无数星号,您可以使用 reduce 将任意数量的参数相乘:

for factors in itertools.product(range(1,3), repeat=10):
    product = reduce(lambda x, y: x*y, factors)

一旦您的格式字符串变得笨拙,您可以依靠 join 将因素串在一起:

if product == 512:
    #use `map` to turn the factors into strings, first
    print "factors: " + ",".join(map(str, factors))

关于python - 简化 Python 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030190/

相关文章:

product - Dynamics AX 2012-更改产品收货的总分类帐过帐

new-operator - 如何推广新产品/服务?

Magento 索引管理问题,产品未显示在类别页面中

math - 有效存储质数

c++ - 除数算法

python - 如何在azure hdinsight pyspark3内核上安装python包?

python - 从包含缺失值的文本文件中读取数据

python - 对于 python 字符串连接,%s 是否比 + 快

python - 如何在 python 中使用 readlines 仅在回车时拆分?

c++ - C++ 中的费马分解