You misses an n
inside len()
. The error
TypeError: len() takes exactly one argument (0 given)
tells you exactly what is wrong (if you fix the indentation problems of your code postet above).
You can streamline your code by using itertools.combinations
. If you add some parameters to a function, you can generalize the problem searching as well - to get all combinations of n numbers from your list that add up to your targetvalue.
from itertools import combinations
def is_sum_of_n_numbers(data ,target_value, num_elem):
"""Returns 'True' if any combinatin of 'num_elem'ents
from 'data' sums to 'target_value'"""
return any(sum(x)==target_value for x in combinations(data, num_elem))
def find_sum_in_combination(data, target_value, num_elem):
"""Returns all combinations of 'num_elem'ent-tuples from 'data'
that sums to 'target_value'"""
return [x for x in combinations(data,num_elem) if sum(x) == target_value]
Get all of them:
d = [1,2,3,4,5]
for numbers in range(1,6):
for s in range(1,sum(d)+1):
result = find_sum_in_combination(d,s,numbers)
if result:
print(f"Sum {s} from {d} with {numbers} numbers: ", result)
Output:
Sum 1 from [1, 2, 3, 4, 5] with 1 numbers: [(1,)]
Sum 2 from [1, 2, 3, 4, 5] with 1 numbers: [(2,)]
Sum 3 from [1, 2, 3, 4, 5] with 1 numbers: [(3,)]
Sum 4 from [1, 2, 3, 4, 5] with 1 numbers: [(4,)]
Sum 5 from [1, 2, 3, 4, 5] with 1 numbers: [(5,)]
Sum 3 from [1, 2, 3, 4, 5] with 2 numbers: [(1, 2)]
Sum 4 from [1, 2, 3, 4, 5] with 2 numbers: [(1, 3)]
Sum 5 from [1, 2, 3, 4, 5] with 2 numbers: [(1, 4), (2, 3)]
Sum 6 from [1, 2, 3, 4, 5] with 2 numbers: [(1, 5), (2, 4)]
Sum 7 from [1, 2, 3, 4, 5] with 2 numbers: [(2, 5), (3, 4)]
Sum 8 from [1, 2, 3, 4, 5] with 2 numbers: [(3, 5)]
Sum 9 from [1, 2, 3, 4, 5] with 2 numbers: [(4, 5)]
Sum 6 from [1, 2, 3, 4, 5] with 3 numbers: [(1, 2, 3)]
Sum 7 from [1, 2, 3, 4, 5] with 3 numbers: [(1, 2, 4)]
Sum 8 from [1, 2, 3, 4, 5] with 3 numbers: [(1, 2, 5), (1, 3, 4)]
Sum 9 from [1, 2, 3, 4, 5] with 3 numbers: [(1, 3, 5), (2, 3, 4)]
Sum 10 from [1, 2, 3, 4, 5] with 3 numbers: [(1, 4, 5), (2, 3, 5)]
Sum 11 from [1, 2, 3, 4, 5] with 3 numbers: [(2, 4, 5)]
Sum 12 from [1, 2, 3, 4, 5] with 3 numbers: [(3, 4, 5)]
Sum 10 from [1, 2, 3, 4, 5] with 4 numbers: [(1, 2, 3, 4)]
Sum 11 from [1, 2, 3, 4, 5] with 4 numbers: [(1, 2, 3, 5)]
Sum 12 from [1, 2, 3, 4, 5] with 4 numbers: [(1, 2, 4, 5)]
Sum 13 from [1, 2, 3, 4, 5] with 4 numbers: [(1, 3, 4, 5)]
Sum 14 from [1, 2, 3, 4, 5] with 4 numbers: [(2, 3, 4, 5)]
Sum 15 from [1, 2, 3, 4, 5] with 5 numbers: [(1, 2, 3, 4, 5)]
Doku: