python - 找出所有可能的偶数或奇数组合并对结果进行数学运算
问题描述
我试图从三个列表中的每一个中取一个整数来找到所有可能的组合。组合必须包含所有偶数或所有奇数。
然后我想找到每个组合中整数的平方和。
最后,我想创建一个字典,使用这个值作为键,并使用它作为存储值的组合。
例如对于组合 (1,3,1):键是整数 11(来自总和 (1^2) + (3^2) + (1^2)),存储的值是 (1, 3,1)
到目前为止我的代码:
lists = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]
combos = np.array([list(i) for i in np.array(np.meshgrid(*values)).T.reshape(-1,len(values))])
这需要三个列表,每个列表都包含整数 0-6
并使用每个列表中的一个元素来创建三个整数的组合
所有可能的组合结果:[0,0,0], [0,1,0], [0,2,0], [1,0,0] ... [6,6,6]
解决方案
一种解决方案。
代码
from itertools import product
lsts = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]
# Product generates all combinations of taking one from each list
combos = product(*lsts)
# We filter for the combinations with all odd or even
# using generator i.e. () but could have been a list i.e. []
valid = (c for c in combos if all(x%2==0 for x in c) or all(x%2==1 for x in c))
# Dictionary key is sum of the squares of c
d = {sum(map(lambda i : i * i, c)) : c for c in valid}
# Pretty Print result
import pprint
pprint.pprint(d)
输出
{0: (0, 0, 0),
3: (1, 1, 1),
4: (2, 0, 0),
8: (2, 2, 0),
11: (3, 1, 1),
12: (2, 2, 2),
16: (4, 0, 0),
19: (3, 3, 1),
20: (4, 2, 0),
24: (4, 2, 2),
27: (5, 1, 1),
32: (4, 4, 0),
35: (5, 3, 1),
36: (6, 0, 0),
40: (6, 2, 0),
43: (5, 3, 3),
44: (6, 2, 2),
48: (4, 4, 4),
51: (5, 5, 1),
52: (6, 4, 0),
56: (6, 4, 2),
59: (5, 5, 3),
68: (6, 4, 4),
72: (6, 6, 0),
75: (5, 5, 5),
76: (6, 6, 2),
88: (6, 6, 4),
108: (6, 6, 6)}
推荐阅读
- twilio - 当座席将呼叫者置于保留状态时,我如何更改音乐?
- python - 用我开始的按钮打破循环?
- php - 需要帮助选择带有 xsl:choose 和 xsl/when 的 XSLT
- java - 输出流空指针
- docker - 如何使本地主机可以访问我的 VS Code 开发/远程容器端口?
- pycharm - 无法让 keras 模型或 tf.data.experimental.CsvDataset 在 Pycharm 上运行
- python - 可以根据语言 cookie 内容有条件地构建烧瓶“WTForms 类”
- r - 如何在R中的第二个分隔符之后提取字符串
- redhawksdr - 我应该使用 BUILKIO 从 REDHAWK 设备输出 Vita49 数据包吗?
- ios - 如何上线核心数据重量级迁移?