我有一个元素从0到3不等的列表。我想要创建一个列表的模式,如果有0,我不改变任何值,如果有1,则改变值从0和1。如果有2,则改变它的值从0、1和2。这听起来可能很混乱,但简单地说,我想生成这样的模式:
input_list = [0, 0, 0, 0]
output = [0, 0, 0, 0] # Since input only has 0s we do not permute their values.
input_list = [1,0,0,0]
output = [0,0,0,0], [1,0,0,0] # We can permute the values of the 1 present.
input_list = [1,0,0,1]
output = [0,0,0,0], [1,0,0,0], [0,0,0,1], [1,0,0,1]在列表包含2的情况下,我们从0-1-2更改它的值。
input_list = [2,0,0,0]
output = [0,0,0,0], [1,0,0,0], [2,0,0,0]
input_list = [1,0,0,2]
output = [0,0,0,0], [1,0,0,0], [0,0,0,1], [1,0,0,1], [0,0,0,2], [1,0,0,2]如果列表中有3,则类似的输出。
我有点不确定该如何处理这个问题。任何帮助都会很好。
这不是家庭作业问题。我只是在研究项目,需要一个类似的模式进行一些模拟。复杂性不是一个问题,但会倾向于低复杂度的解决方案。:D
发布于 2019-10-29 16:37:15
from itertools import product
input_list = [1,0,0,2]
list( product(*(range(x+1) for x in input_list)) )输出:
[(0, 0, 0, 0),
(0, 0, 0, 1),
(0, 0, 0, 2),
(1, 0, 0, 0),
(1, 0, 0, 1),
(1, 0, 0, 2)]发布于 2019-10-29 16:24:40
以下是一个可能的解决方案:
input_list = [1, 0, 0, 2]
outputs = []
def get_outputs(input_list):
if len(input_list) == 0:
return [[]]
first = input_list[0]
outputs = get_outputs(input_list[1:])
result = [[0] + out for out in outputs]
if first >= 1:
result += [[1] + out for out in outputs]
if first >= 2:
result += [[2] + out for out in outputs]
if first == 3:
result += [[3] + out for out in outputs]
return result
print(get_outputs(input_list))解决方案没有优化。在大名单上运行可能需要一段时间。任何改进或建议都将受到高度赞赏。
https://stackoverflow.com/questions/58611086
复制相似问题