3

Everytime I try to solve some math problem such as finding a specific product of certain number of factors I do this in 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)

It is very straightforward and gets the job done fast in this example, but I was wondering if you guys know an easier or simpler way to write this. Any ideas on how to do this without using that many for iterations or repeating almost the same code over and over. These is obviously for 3 factors, but the more factors I add the longer and more repetitive the code keeps getting. Any ideas on how to simplify code for this simple type of problem? thanks

4

2 回答 2

5

Itertool 的笛卡尔积模拟了多个嵌套 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))
于 2013-06-10T18:16:02.043 回答
4

y通过从 开始避免重复x。计算z而不是运行另一个循环。

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

对于更多因素,我会使用递归函数。

于 2013-06-10T18:27:09.630 回答