如何打印原始输入列表的索引

时间:2018-01-20 04:29:29

标签: python algorithm combinations

我试图让所有可能的组合等于目标总和。我的脚本完美地做到了这一点,但是我需要输出来显示原始索引号。我输出的脚本输出正确的数字组合,但不是正确的索引。

正确输出的示例:

input=([1, 2, 3, 4], target_sum=6) output=[1,3], [0,1,2]

我的代码如下(source):

numbers = [1,2,3,4,5]
target = 6    

def calc_combo(input_number, target_sum, partial=[]):
    total = sum(partial)
    idx = []
    index = [[num,indices] for indices,num in enumerate(partial)]

    if total == target_sum:    
        for i in index:
            idx.append(i)
        print(str(idx) + " = " + str(target_sum))     

    if total >= target_sum:
        return

    for i in range(len(input_number)):
        n = input_number[i]
        remaining = input_number[i+1:]
        calc_combo(remaining, target_sum, partial + [n])

calc_combo(numbers, target)

其中给出了以下输出:

[[1, 0], [2, 1], [3, 2]] = 6
[[1, 0], [5, 1]] = 6
[[2, 0], [4, 1]] = 6

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用 list.index(elem) 获取列表中元素的索引

在您的代码中,您可以替换

index = [[num,indices] for indices,num in enumerate(partial)]

index = [[num,input_number.index(num)] for num in partial]

否则,您可以使用以下代码,该代码考虑所有组合并且不使用函数index并返回(nums,索引)列表,而不是打印(num,index)列表的列表):

def combo(options, target):
    ret = []
    for level in range(len(options)):
        for i,c in enumerate(options):
            for j,g in enumerate(options[i+1:]):
                if i+1+j+level <= len(options):
                    combo = [c,*options[i+1+j:i+1+j+level]]
                    if sum(combo) == target:
                        index = [i,*list(range(i+1+j,i+1+j+level))]
                        ret.append((combo, index))
                if level == 0:
                    break
    return ret

Python 3的预期输出:

>>>combo(list(x*2**-2 for x in range(-4,5,1)), 2)
[([0.25, 0.75, 1.0], [5, 7, 8]),
 ([-0.25, 0.5, 0.75, 1.0], [3, 6, 7, 8]),
 ([-0.5, 0.25, 0.5, 0.75, 1.0], [2, 5, 6, 7, 8]),
 ([-0.5, 0.0, 0.25, 0.5, 0.75, 1.0], [2, 4, 5, 6, 7, 8])]