[英]Get all permutations that pad a list with zeroes
I have a list ls
of length n
and want to get all lists of length m
(where m > n) that contain ls
in the same order, plus (m - n) zeroes, inserted at each possible combination of positions.我有一个长度为n
的列表ls
并且想要获取所有长度为m
(其中 m > n)的列表,其中包含相同顺序的ls
,加上 (m - n) 个零,插入到每个可能的位置组合中。
For example: ls = [1, 2, 3]
and m = 4
should return例如: ls = [1, 2, 3]
和m = 4
应该返回
[[1, 2, 3, 0],
[1, 2, 0, 3],
[1, 0, 2, 3],
[0, 1, 2, 3]]
and ls = [1, 2, 3]
and m = 5
should return和ls = [1, 2, 3]
和m = 5
应该返回
[[1, 2, 3, 0, 0],
[1, 2, 0, 3, 0],
[1, 2, 0, 0, 3],
[1, 0, 2, 3, 0],
[1, 0, 2, 0, 3],
[1, 0, 0, 2, 3],
[0, 1, 2, 3, 0],
[0, 1, 2, 0, 3],
[0, 1, 0, 2, 3],
[0, 0, 1, 2, 3]]
The solution should be fast and memory efficient - in particular, it should avoid generating duplicate solutions.解决方案应该是快速和内存高效的——特别是,它应该避免生成重复的解决方案。 Any help is appreciated!任何帮助表示赞赏!
A working (but inefficient) attempt:一个有效(但效率低下)的尝试:
ls = [1, 2, 3]
m = 4
from itertools import permutations
n = len(ls)
results = []
for t in set(permutations('1' * n + '0' * (m - n))):
idxs = [i for i, j in enumerate(t) if j == '1']
result = [0] * m
for idx, value in zip(idxs, ls):
result[idx] = value
results.append(result)
Use itertools.combinations
to generate every combination of places to insert zeroes.使用itertools.combinations
生成每个位置组合以插入零。 Then use a list comprehension to select 0 or the next original element to build the new list.然后使用列表推导选择 0 或下一个原始元素来构建新列表。
# Pad list orig with zeroes, out to "m" total elements.
from itertools import combinations
orig = [1, 2, 3]
m = 5
n = len(orig)
padded = []
for pad_idx in combinations(range(m), m-n):
t = orig[:]
padded.append( [0 if i in pad_idx else t.pop(0)
for i in range(m)] )
print(padded)
Output (formatted for readability):输出(格式化的可读性):
[[0, 0, 1, 2, 3],
[0, 1, 0, 2, 3],
[0, 1, 2, 0, 3],
[0, 1, 2, 3, 0],
[1, 0, 0, 2, 3],
[1, 0, 2, 0, 3],
[1, 0, 2, 3, 0],
[1, 2, 0, 0, 3],
[1, 2, 0, 3, 0],
[1, 2, 3, 0, 0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.