How to Sum a Numeric List Elements

Summing elements in a list

You can sum numbers in a list simply with the sum() built-in:

sum(your_list)

It will sum as many number items as you have. Example:

my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]

sum(my_list)
91

For your specific case:

For your data convert the numbers into int first and then sum the numbers:

data = ['5', '4', '9']

sum(int(i) for i in data)
18

This will work for undefined number of elements in your list (as long as they are "numbers")

Thanks for @senderle's comment re conversion in case the data is in string format.

how to sum two numbers in a list?

use itertools.combinations which combines the elements of your list into non-repeated couples, and check if the sum matches. If it does, print the positions of the terms:

import itertools

integer_array = [2, 8, 4, 7, 9, 5, 1]
target = 10
for numbers in itertools.combinations(integer_array,2):
if sum(numbers) == target:
print([integer_array.index(number) for number in numbers])

python sum a value to all the elements in a list

I think the way you have it is about as Pythonic as you can get working with lists. Any other option I can think of sacrifices either efficiency or legibility. You could do something like

list(map(y.__add__, my_list))

OR

list(map(partial(operator.add, y), my_list))

If you use an external dependency like numpy:

list(np.array(my_list) + y)

That's definitely not more efficient on its own though. It would only make sense if you wanted np.array(my_list) anyway, and didn't convert back to list.

How to sum up elements in list in a moving range

Try this (lst being your list and n being your range):

print(max(sum(lst[i:i+n+1]) for i in range(len(lst)-n)))

So for example:

>>> lst = [5.8, 1.2, 5.8, 1.0, 6.9, 0.8, 6.0, 18.4]
>>> n = 5
>>> print([sum(lst[i:i+n+1]) for i in range(len(lst)-n)])
[21.5, 21.7, 38.9]
>>> print(max(sum(lst[i:i+n+1]) for i in range(len(lst)-n)))
38.9

Sum all numbers in a given range of a given list Python

It seems like you want do roll your own solution. You can do it like this (based on the code you had in your question):

def sumRange(L,a,b):                                                                                                                                                                                                
sum = 0
for i in range(a,b+1,1):
sum += L[i]
return sum

L = [6,3,4,2,5]
a = 1
b = 3

result = sumRange(L,a,b)

print "The result is", result

This program prints

The result is 9

Find Distinct parts of List that Sum are equal to the given Number

Your original function was generating properly the possible combinations. The only problem was that you were printing it, instead of saving it in a list to use later.

I modified it so it saves the result into a list, that can be input to a function that generates all permutations (also implemented recursively) of a list.

Overall, the approach is:

  1. Generate all combinations of 1, 2, ... n numbers that sum to less than goal
  2. Generate all the permutations of these combinations (this step seems useless, because sum is commutative, but I'm assuming that is the definition of your problem)

Note that this is an instance of the Subset Sum Problem, which is a difficult optimisation problem. The solution below does not scale well for large sets.

def unique_combination(in_list, goal, current_sum, current_path, accumulator):
# Does a depth-first search of number *combinations* that sum exactly to `goal`
# in_list is assumed sorted from smaller to largest

for idx, current_element in enumerate(in_list):
next_sum = current_sum + current_element
if next_sum < goal:
next_path = list(current_path) # list is needed here to create a copy, as Python has a pass by reference semantics for lists
next_path.append(current_element)
unique_combination(in_list[idx+1:], goal, next_sum, next_path, accumulator)
elif next_sum == goal: # Arrived at a solution
final_path = list(current_path)
final_path.append(current_element)
accumulator.append(final_path)
else: # Since in_list is ordered, all other numbers will fail after this
break
return accumulator

def permutations(elements):
# Returns a list of all permutations of `elements`, calculated recursively
if len(elements) == 1:
return [elements]
result = []
for idx, el in enumerate(elements):
other_elements = elements[:idx] + elements[idx+1:]
all_perms = [[el] + sub_perms for sub_perms in permutations(other_elements)]
result.extend(all_perms)
return result

def myFunc(input_list, goal):
# Sort the given elements
input_list.sort()
combinations = unique_combination(input_list, goal, 0, [], [])

result = []
for comb in combinations:
result.extend(permutations(comb))
return result

def print_results(results):
for el in results:
print(tuple(el)) # to get the parentheses

# Input:
a = [1,2,3,4,6,7,8]
k = 8
all_permutations = myFunc(a, k)
print_results(all_permutations)

# (1, 3, 4)
# (1, 4, 3)
# (3, 1, 4)
# (3, 4, 1)
# (4, 1, 3)
# (4, 3, 1)
# (1, 7)
# (7, 1)
# (2, 6)
# (6, 2)
# (8,)


Related Topics



Leave a reply



Submit