Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Partial sum of numbers [duplicate]

Tags:

python

can you help me with code which returns partial sum of numbers in text file? I must import text file, then make a code for partial sums without tools ..etc.

My input:

4
13
23
21
11

The output should be (without brackets or commas):

4 
17
40
61 
72

I was trying to make code in python, but could only do total sum and not partial one. If i use the += operator for generator, it gives me an error!

like image 794
user1798558 Avatar asked Nov 04 '12 19:11

user1798558


People also ask

How do you find the sum of multiple numbers in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

How do you sum a range in Python?

To sum all numbers in a range:Use the range() class to get a range of numbers. Pass the range object to the sum() function. The sum() function will return the sum of the integers in the range.

What is a partial sum of a series?

A partial sum of an infinite series is the sum of a finite number of consecutive terms beginning with the first term. When working with infinite series, it is often helpful to examine the behavior of the partial sums.

What is sum () in Python?

Python sum() Function The sum() function returns a number, the sum of all items in an iterable.


1 Answers

Well, since everyone seems to be giving their favourite idiom for solving the problem, how about itertools.accumulate in Python 3:

>>> import itertools
>>> nums = [4, 13, 23, 21, 11]
>>> list(itertools.accumulate(nums))
[4, 17, 40, 61, 72]
like image 97
DSM Avatar answered Oct 27 '22 10:10

DSM