python - 条件 (a*a + b*b = c*c) 在使用 python 的列表中满足
问题描述
我需要知道列表中的元素是否满足条件
、a*a + b*b = c*c
where和是以下列表中的任何元素:a
b
c
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
推荐阅读
- database - 测试 Postgres 数据库的可扩展性
- reactjs - 反应如何在状态中存储道具
- javascript - Stripe - 如何使用 react-stripe 创建可以接受付款的帐户?
- google-cloud-platform - 如何从前端移动客户端发布到 Google Pub/Sub?
- android - 如何将偏移量应用于 android (Kotlin) 中的 Contacts Provider 查询?
- rust - Rust 为闭包调用 trait 别名
- java - 如何使没有安装java的人可以使用java应用程序
- python - 在某些条件下迭代集合的最有效方法是什么?
- perl - 如何在 vscode 的 PerlDebug 中查看 hashmap 变量?
- azure-devops - 在 python 中的 Azure Function 中从 Azure Blob 存储读取数据