Pergunta

So here is the code that i have so far. It works and returns true if the sum exists but i cant seem for the life of me to find a way for it to print out the integers it used to find the sum. Is there a way i can re write it to get it to do that along with true or how should i write the code so it can do that?

from itertools import combinations

def com_subset_sum(seq, target):
    if target == 0 or target in seq:
        return True

    for r in range(2, len(seq)):
        for subset in combinations(seq, r):
            if sum(subset) == target:
                return True
    return False 
Foi útil?

Solução

Just use print to see it's content:

Example:

from itertools import combinations

def com_subset_sum(seq, target):
    if target == 0 or target in seq:
        return True

    for r in range(len(seq),1,-1):
        for subset in combinations(seq, r):
            if sum(subset) == target:
                print subset
                return True
    return False


print com_subset_sum([1,3,5,1,6,8,7],10)

output:

(1, 3, 5, 1)
True

Outras dicas

What about something like

def ssum(numbers, target):
    return [x for r in xrange(2,len(numbers)) for x in combinations(numbers,r) if sum(x)==target]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top