包含重复项的python排列

3 投票
1 回答
2261 浏览
提问于 2025-04-18 09:21

我写了一个程序,用来判断一个长方体的表面积和面积是否相等。

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 个回答

5

我觉得你应该使用 itertools.product,而不是 permutations

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

这个方法会把从 199 的三个数字的所有可能组合都列出来,包括那些 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)

撰写回答