car*_*are 3 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))
Run Code Online (Sandbox Code Playgroud)
这会迭代数字 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
Run Code Online (Sandbox Code Playgroud)
现在,如果你仔细观察,没有一个测量值是相同的,例如我永远不会得到答案(不是正确的答案)
length = 3, height = 3, width = 3
Run Code Online (Sandbox Code Playgroud)
因为它只迭代数字一次。我怎样才能包含这些“双重”答案?
我认为你想要itertools.product而不是permutations:
for l, w, h in itertools.product(range(1, 100), repeat=3):
Run Code Online (Sandbox Code Playgroud)
这将详尽地遍历从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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2247 次 |
| 最近记录: |