python - 与特殊值交织的排列

标签 python python-3.x permutation python-3.6

我在试图解决这个问题时遇到了真正的大脑障碍。我正在尝试编写一个函数,该函数将返回列表的所有排列,并与一些特殊值交错。

函数签名:

def interleaved_permutations(values, num_special_values)

一个例子:

>>> interleaved_permutations([1,2,3,4], 2)
[1,x,x,2,3,4]
[1,x,2,x,3,4]
[1,x,2,3,x,4]
[1,2,x,x,3,4]
...

一个额外的要求是特殊值不能位于列表中的第一个或最后一个。

我知道一定有办法处理一些疯狂的 itertools foo,但我无法想出任何远程接近的方法。我得到的最接近的只是使用 itertools.permutations

获取输入值的排列

我希望比我更Python的人能够提供帮助!

最佳答案

一种方法是使用 itertools.combinations 来选择插入后特殊值的位置:

from itertools import permutations, combinations

def interleaved(values, num_special_values):
    width = len(values) + num_special_values
    special = 'x'
    for perm in permutations(values):
        for pos in combinations(range(1, width-1), num_special_values):
            it = iter(perm)
            yield [special if i in pos else next(it)
                   for i in range(width)]

这给了我

In [31]: list(interleaved([1,2,3], 2))
Out[31]: 
[[1, 'x', 'x', 2, 3],
 [1, 'x', 2, 'x', 3],
 [1, 2, 'x', 'x', 3],
 [...]
 [3, 'x', 'x', 2, 1],
 [3, 'x', 2, 'x', 1],
 [3, 2, 'x', 'x', 1]]

In [32]: list(interleaved([1,2,3,4], 2))
Out[32]: 
[[1, 'x', 'x', 2, 3, 4],
 [1, 'x', 2, 'x', 3, 4],
 [1, 'x', 2, 3, 'x', 4],
 [...]
 [4, 3, 'x', 2, 'x', 1],
 [4, 3, 2, 'x', 'x', 1]]

关于python - 与特殊值交织的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950769/

相关文章:

python - 正则表达式 - 跟踪号码 2018

python - 为 python 3.4 安装 mechanize

python - 访问 Numpy 3 维数组中的短对角线元素

Python:从命令行运行时包含库文件夹

php - 我可以使用 PHP 随机字符串随机播放获得的不同字符串的数量

python - 如何保存Animation.Artist动画?

python - 如何从同一目录导入python类文件?

python-3.x - Odoo 13 : How to solve CacheMiss Exception

C++遍历所有邻居排列

c - 从 C 中的 n 生成 k 个排列