我正在嘗試制作一個計算四元組(a^3 b^3=c^3 d^3)的程式。使用我當前的代碼,我在 [1, 15] 的域內得到了 8 個答案,但是正如您將在輸出中看到的那樣,答案都是相同的,但順序卻發生了變化。我的問題是:如何過濾掉重復項并只得到一個答案?(對不起,如果我用我凌亂的代碼讓你心臟病發作)
代碼:
interval = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
solutions = []
for a in interval:
for b in interval:
for c in interval:
for d in interval:
if a != c and b !=d:
if a != d and b != c:
if a**3 b**3 == c**3 d**3:
temp = [a, b, c, d]
solutions.append(temp)
print(solutions)
輸出:
[[1, 12, 9, 10], [1, 12, 10, 9], [9, 10, 1, 12], [9, 10, 12, 1], [10, 9, 1, 12], [10, 9, 12, 1], [12, 1, 9, 10], [12, 1, 10, 9]]
提前致謝!
uj5u.com熱心網友回復:
正如評論中提到的ShadowRanger,itertools.combinations是使用的工具:
from itertools import combinations
solutions = []
for (a,b),(c,d) in combinations(combinations(range(1,16),2),2):
if a**3 b**3 == c**3 d**3:
solutions.append((a,b,c,d))
print(solutions)
印刷 [(1, 12, 9, 10)]
uj5u.com熱心網友回復:
您可以使用itertools.combinations更少的重復從串列中生成有序的 4 元組。但它確實提出了一個新問題,您實際上并不想要有序值,因為您的方程不可能滿足a < b < c < d,因為您將兩個最小值的立方相加,這兩個最小值總是小于兩個最大值的立方體。
這確實使我們獲得了一個關鍵的見解。我們從不想將四元組中的兩個最大值和兩個最小值配對。此外,我們甚至不想將前兩個值中較小的值與后兩個值中較小的值配對,因為同樣,它們的立方體總是比另一對小。所以我們總是可以將最大值與最小值配對,并將兩個中間值配對。因此,如果它們是有序的 ( a < b < c < d),則您需要a**3 d**3和b**3 c**3。這是我如何在代碼中做到這一點:
import itertools as it
interval = range(1, 16)
results = [[a, d, b, c] for a, b, c, d in it.combinations(interval, 4)
if a**3 d**3 == b**3 c**3]
uj5u.com熱心網友回復:
您還可以將訂單添加到您的解決方案中。例如,根據您的功能,您可以將此行添加到您的條件中:
if a < b and c < d and a < c:
那么你只有:
Output : [[1, 12, 9, 10]]
uj5u.com熱心網友回復:
這是一個涉及itertools.product和集合集合的解決方案:
from itertools import product
interval = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
solutions = set()
for a, b, c, d in product(interval, repeat=4):
if a != c and b != d and a != d and b != c:
if a ** 3 b ** 3 == c ** 3 d ** 3:
left_side = frozenset({a, b})
right_side = frozenset({c, d})
equality = frozenset({left_side, right_side})
solutions.add(equality)
print(solutions)
這使得使用的事實,a并且b可以在不影響平等互換,同樣也適用于c和d,并且(a, b)可以互換(c, d)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/317969.html
標籤:Python
下一篇:如何在不寫入磁盤的情況下解壓縮?
