Skip to main content
 首页 » 编程设计

python排列,包括重复

2024年11月01日8dflying

我创建了一个程序来确定长方体的表面积何时与面积相同。

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 

因为它只遍历数字一次。如何包含这些“双重”答案?

请您参考如下方法:

我想你想要itertools.product而不是排列:

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)