条件(a * a + b * b = c * c)使用python在列表中满足

时间:2018-05-31 21:36:01

标签: python python-3.x list mathematical-expressions

我需要知道列表中的元素是否满足条件  a*a + b*b = c*c,其中abc是以下列表中的任何元素:

original_list =[8,5,73,3,34,4,23,73]

数学上,3*3 + 4*4 = 5*5,但不确定如何在python中遍历列表以满足该条件。

3 个答案:

答案 0 :(得分:2)

您可以使用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。虽然我们并不真正关心ab的相对顺序,但c不小于其中任何一个的事实是您正在进行的测试的先决条件

答案 1 :(得分:1)

这个问题围绕数学和算法而不是pythonism。我在下面提出的解决方案具有O(n**2)的复杂性。

想法是颠倒函数(x,y)=&gt; 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))

答案 2 :(得分:0)

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)]