简体   繁体   中英

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

Create a function check_sum_100(L)

I am able to find the sum of elements that add up to 100 when the elements form sub-array. But I am not able to find list of elements like [99,1] .

Here is what I tried to implement:

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)

Use itertools.combinations to get sublists of varying length and check for the sum:

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

You can use recursion for this sort of problem:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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