python排列,包括重复

时间:2014-06-10 21:24:41

标签: python permutation

我创建了一个程序,用于确定长方体的表面积何时与该区域相同。

from itertools import permutations

def area(l, h, w):
    return(l*h*w)

def surf_area(l, h, w):
    return(((l*h)+(l*w)+(w*h))*2)

for length, height, width in permutations(range(1,100),3):
    if area(length, height, width)== surf_area(length, height, width):
        print("length = {}, height = {}, width = {}".format(length,height,width))

这将遍历数字1-100并将它们作为长方体的高度长度和宽度,并仅返回具有相同面积和表面积的答案

这会产生:

length = 3, height = 7, width = 42
length = 3, height = 8, width = 24
length = 3, height = 9, width = 18
length = 3, height = 10, width = 15
length = 3, height = 15, width = 10
length = 3, height = 18, width = 9
length = 3, height = 24, width = 8
length = 3, height = 42, width = 7
length = 4, height = 5, width = 20
length = 4, height = 6, width = 12
length = 4, height = 12, width = 6
length = 4, height = 20, width = 5
length = 5, height = 4, width = 20
length = 5, height = 20, width = 4
length = 6, height = 4, width = 12
length = 6, height = 12, width = 4
length = 7, height = 3, width = 42
length = 7, height = 42, width = 3
length = 8, height = 3, width = 24
length = 8, height = 24, width = 3
length = 9, height = 3, width = 18
length = 9, height = 18, width = 3
length = 10, height = 3, width = 15
length = 10, height = 15, width = 3
length = 12, height = 4, width = 6
length = 12, height = 6, width = 4
length = 15, height = 3, width = 10
length = 15, height = 10, width = 3
length = 18, height = 3, width = 9
length = 18, height = 9, width = 3
length = 20, height = 4, width = 5
length = 20, height = 5, width = 4
length = 24, height = 3, width = 8
length = 24, height = 8, width = 3
length = 42, height = 3, width = 7
length = 42, height = 7, width = 3

现在,如果你仔细观察,没有一个测量值是相同的,例如我永远不会得到答案(不正确答案)

length = 3, height = 3, width = 3

因为它只迭代数字一次。我怎样才能包含这些“加倍”的答案?

1 个答案:

答案 0 :(得分:2)

我认为你想要itertools.product而不是permutations

for l, w, h in itertools.product(range(1, 100), repeat=3):

这将详尽地检查1 - 99中三个数字的所有可能组合,包括l == w == h的情况。

一个较小的例子:

>>> for l, w, h in itertools.product(range(1, 3), repeat=3):
    print(l, w, h)


(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)