我需要知道列表中的元素是否满足条件
、a*a + b*b = c*cwhere和是以下列表中的任何元素:abc
original_list =[8,5,73,3,34,4,23,73]
在数学上3*3 + 4*4 = 5*5,,但不确定如何在 python 中遍历列表以满足该条件。
我需要知道列表中的元素是否满足条件
、a*a + b*b = c*cwhere和是以下列表中的任何元素:abc
original_list =[8,5,73,3,34,4,23,73]
在数学上3*3 + 4*4 = 5*5,,但不确定如何在 python 中遍历列表以满足该条件。
您可以使用以下方法遍历列表中的项目itertools.combinations:
import itertools
for a, b, c in itertools.combinations(sorted(original_list), 3):
if a*a + b*b == c*c:
print("Pythagorean triple found:", a, b, c) # or whaver...
请注意,我在将原始列表传递给combinations. 这确保了a <= b <= c. 虽然我们并不真正关心 and 的相对顺序a,但不小于它们中的任何一个b的事实是您正在进行测试的先决条件。c
这个问题更多地围绕数学和算法而不是pythonisms。我在下面提出的解决方案具有复杂性O(n**2)。
想法是反转函数 (x, y) => x * x + y * y,其中搜索空间是原始列表与自身的叉积。然后,使用 Python 集合运算符,计算应用程序图像和可接受的正方形之间的交集。最终,使用反向应用程序来重建三元组。
from collections import defaultdict
original_list = [8, 5, 73, 3, 34, 4, 23, 73]
uniq = sorted(set(original_list))
antecedents = defaultdict(lambda: []) # Reverse mapping
for i, left in enumerate(uniq):
for right in uniq[i+1:]:
key = left * left + right * right
antecedents[key].append((left, right))
# The keys of antecedents are sum of squares
uniq_squares = set([ x * x for x in uniq ])
common_keys = uniq_squares & antecedents.keys()
for key in common_keys:
sqrt = int(0.5 + key**0.5)
key_antecedents = antecedents[key]
for (left, right) in key_antecedents:
print("Found triplet:", (left, right, sqrt))
Python代码
[(a,b,c) for a in original_list for b in original_list for c in original_list if a*a+b*b==c*c]
输出:
[(3, 4, 5), (4, 3, 5)]