具有 16 个整数的列表的排列,但仅当满足 4 个条件时

Olb*_*a12 6 python combinations permutation constraint-satisfaction

我有一个整数列表

keys = [18, 99, 86, 61, 66, 81, 98, 19, 91, 16, 69, 88, 89, 68, 11, 96]
Run Code Online (Sandbox Code Playgroud)

我想找到这个列表的所有排列,这样对于每个排列

  1. 元素 0 到 3 加起来为 264,

  2. 元素 4 到 7 加起来为 264,

  3. 元素 8 到 11 加起来为 264 和

  4. 元素 12 到 15 广告最多 264。

目前我有以下策略

  1. 使用 itertools.permutations 计算所有排列

  2. 检查哪些排列满足我的条件

是否有另一种性能更好的策略?

Grz*_*ski 0

这应该会快一点,因为我限制了我们从中获得组合的元素数量(我只调用组合一次)。这keys也利用了以下的独特性:

import itertools
import numpy as np
def foo():
    keys = [18, 99, 86, 61, 66, 81, 98, 19, 91, 16, 69, 88, 89, 68, 11, 96]
    n=4
    s=264
    lst=[el for el in itertools.combinations(keys, n) if sum(el)==s]
    for el in itertools.product(lst,repeat=4):
        if len(set(np.array(el).ravel()))==16:
            yield np.array(el).ravel()

for el in foo():
    print(el)
Run Code Online (Sandbox Code Playgroud)

输出:

[18 99 86 61 66 81 98 19 91 16 69 88 89 68 11 96]
[18 99 86 61 66 81 98 19 91 16 89 68 69 88 11 96]
[18 99 86 61 66 81 98 19 69 88 11 96 91 16 89 68]
[18 99 86 61 66 81 98 19 89 68 11 96 91 16 69 88]
[18 99 86 61 66 98 89 11 81 19 68 96 91 16 69 88]
[18 99 86 61 66 98 89 11 91 16 69 88 81 19 68 96]
[18 99 86 61 66 19 91 88 81 98 16 69 89 68 11 96]
[18 99 86 61 66 19 91 88 89 68 11 96 81 98 16 69]
...
Run Code Online (Sandbox Code Playgroud)

(如果您希望将结果保留为四个四元素元组的格式,则可以删除.ravel()I 行中的内容)yield