【问题标题】:Permutations interleaved with special values与特殊值交错的排列
【发布时间】:2018-04-20 23:06:40
【问题描述】:

我正在努力解决这个问题。我正在尝试编写一个函数,该函数将返回列表的所有排列,并与一些特殊值交错。

函数签名:

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 的人能够提供帮助!

【问题讨论】:

  • 所以项目 [1,2,3,4] 实际上没有排列?它们是否始终保持 [1,2,3,4] 顺序?
  • 它们实际上是置换的,只要列举足够多的例子就可以看出太多了!虽然这实际上并不难,但您只需要将交错应用于每个排列。我确实遇到了@_@ 的问题

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


【解决方案1】:

一种方法是使用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]]

【讨论】:

  • 就是这样。我试图弄乱 zip() 和 chain() 来做一些疯狂的事情。非常感谢。我知道我不应该在 sprint 计划后的星期五开始这个!
【解决方案2】:

只需从排列列表中过滤掉坏排列即可:

>>> from itertools import permutations
>>> l = [1, 2, 3, 4]
>>> s = ['x', 'y']
>>> def good(x):
...     return x[0] not in s and x[-1] not in s
...
>>> print(*filter(good, permutations(l+s)), sep='\n')
(1, 2, 3, 'x', 'y', 4)
(1, 2, 3, 'y', 'x', 4)
(1, 2, 4, 'x', 'y', 3)
(1, 2, 4, 'y', 'x', 3)
(1, 2, 'x', 3, 'y', 4)
(1, 2, 'x', 4, 'y', 3)
(1, 2, 'x', 'y', 3, 4)
(1, 2, 'x', 'y', 4, 3)
(1, 2, 'y', 3, 'x', 4)
(1, 2, 'y', 4, 'x', 3)
(1, 2, 'y', 'x', 3, 4)
(1, 2, 'y', 'x', 4, 3)
...
(4, 'y', 'x', 2, 3, 1)
(4, 'y', 'x', 3, 1, 2)
(4, 'y', 'x', 3, 2, 1)
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多