繁体   English   中英

给定一个数字列表,检查是否存在加到 100 的数字。将所有这些数字列为列表列表

[英]Given a list of numbers, check if there exists numbers that add to 100. List all those numbers as a list of lists

Input : L=[1,50,16,34,8,42,99]

Output : [[50,8,42],[16,34,50],[99,1],[16,34,42,8]]

创建函数check_sum_100(L)

当元素形成子数组时,我能够找到加起来为 100 的元素的总和。 但我无法找到[99,1]之类的元素列表。

这是我试图实现的:

def check_sum_100(L):
    out=[]
    for i in range(0, len(L)):             
        for j in range(i, len(L)): 
            sum = 0 
            temp = []                       
            for k in range (i, j+1):
                sum = sum + L[k]            
                temp.append(L[k])
            if sum == 100:
                out.append(temp)
    return out


L = [1,50,16,34,8,42,99]

o = check_sum_100(L)

print(o)

使用itertools.combinations获取不同长度的子列表并检查总和:

import itertools

def check_sum_100(L):
    output = list()
    for l in range(len(L)+1):
        for sublist in itertools.combinations(L, l):
            if sum(sublist)==100:
                output.append(sublist)         
    return output

>>> check_sum([1,50,16,34,8,42,99])
[(1, 99), (50, 16, 34), (50, 8, 42), (16, 34, 8, 42)]

您可以对此类问题使用递归:

def check_sum_100(L):
    # inner function looks for a specific sum target and generates combinations
    def check_sum(L,target):
        for i,v in enumerate(L):
            if v == target:       # base condition, a number in L is the target
                yield [v]
            else:
                # check the sublist after this number for sums that equal the remainder
                for o in check_sum(L[i + 1:], target - v):
                    yield [v] + o
    return list(check_sum(L, 100))

L = [1,50,16,34,8,42,99]
print(check_sum_100(L))

输出:

[[1, 99], [50, 16, 34], [50, 8, 42], [16, 34, 8, 42]]
from itertools import combinations as c
L=[1,50,16,34,8,42,99]

#c(L,x) will take all the combinations from 1 digit to length of L in the for loop

[[x for x in list(c(L,x)) if sum(x)==100] for x in range(1,len(L)+1) if [x for x in list(c(L,x)) if sum(x)==100]!=[] ]

#output
[[(1, 99)], [(50, 16, 34), (50, 8, 42)], [(16, 34, 8, 42)]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM