首页 > 解决方案 > 条件 (a*a + b*b = c*c) 在使用 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 中遍历列表以满足该条件。

标签: pythonpython-3.xlistmathematical-expressions

解决方案


您可以使用以下方法遍历列表中的项目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


推荐阅读