【问题标题】:Create a pattern from a list of numbers从数字列表创建模式
【发布时间】:2019-10-29 15:57:35
【问题描述】:

我有一个列表,其元素范围从 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

【问题讨论】:

    标签: python algorithm list sequence


    【解决方案1】:
    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)]
    

    【讨论】:

    • 等等...诀窍是安排图案..? :P 这是最简单的解决方案...谢谢!
    【解决方案2】:

    这是一个可能的解决方案:

    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))
    

    解决方案未优化。在大列表上运行可能需要一段时间。非常感谢任何改进或建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2021-12-05
      • 2021-12-25
      • 2018-12-17
      • 2017-04-18
      • 1970-01-01
      相关资源
      最近更新 更多