python - 给定一个大小为 n 的数组 arr 和一个整数 X。查找数组中是否有一个三元组的总和为给定整数 X
问题描述
给定一个大小为 n 的数组 arr 和一个整数 X。找出数组中是否有一个三元组的总和等于给定的整数 X。
Input:
n = 5, X = 10
arr[] = [1 2 4 3 6]
Output:
Yes
Explanation:
The triplet {1, 3, 6} in
the array sums up to 10.
解决方案
推理的路线是:获取数组 arr 中 3 个数字的所有可能组合。找出 sum=X 的,只打印这些三元组
import numpy as np
import itertools
arr=np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
X=10
combinations=np.array(list(itertools.combinations(arr, 3)))
triplets=combinations[combinations.sum(axis=1)==X]
print(f'Triplets with sum equal to {X} are:\n{triplets}')
输出:
Triplets with sum equal to 10 are:
[[0 1 9]
[0 2 8]
[0 3 7]
[0 4 6]
[1 2 7]
[1 3 6]
[1 4 5]
[2 3 5]]
推荐阅读
- python - Python Pandas Dataframe ValueError:使用可迭代设置时必须具有相等的 len 键和值
- python - 如何隔离小数中的单个数字?
- git - Git 身份验证被破坏
- laravel - 更改个人资料图片 laravel 8
- html - white-space: nowrap 在 Google Chrome 移动设备的底部生成额外的空白空间
- java - 理解弱引用
- javascript - 单击时将活动类切换到按钮
- java - 在循环中执行 jar 的效率有多低?有哪些替代方案?
- javascript - 如何使用 jquery 在 AJAX 中调用警报?
- precision - 如何评价非线性模型的精度?