# Untitled

By: a guest on Apr 29th, 2012  |  syntax: None  |  size: 0.98 KB  |  hits: 10  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. Elegant pythonic cumsum
2. >>> import numpy as np
3. >>> np.cumsum([1,2,3,4,5])
4. array([ 1,  3,  6, 10, 15])
5.
6. def cumsum(it):
7.     total = 0
8.     for x in it:
9.         total += x
10.         yield total
11.
12. >>> list(cumsum([1,2,3,4,5]))
13. >>> [1, 3, 6, 10, 15]
14.
15. a=[1,2,3,4,5]
16.
17. def cumsum(a):
18.     a=iter(a)
19.     cc=[next(a)]
20.     for i in a:
21.         cc.append(cc[-1]+i)
22.     return cc
23.
24. print cumsum(a)
25. "[1, 3, 6, 10, 15]"
26.
27. a=[1,2,3,4,5]
28. def cumsum(a):
29.     for i in range(1,len(a)):
30.         a[i]+=a[i-1]
31.
32. cumsum(a)
33. print a
34. "[1, 3, 6, 10, 15]"
35.
36. a = [1, 2, 3 ,4, 5]
37.
38. # Using list comprehention
39. cumsum = [sum(a[:i+1]) for i in range(len(a))]           # [1, 3, 6, 10, 15]
40.
41. # Using map()
42. cumsum = map(lambda i:  sum(a[:i+1]), range(len(a)))     # [1, 3, 6, 10, 15]
43.
44. def cumsum(vec):
45.     r = [vec[0]]
46.     for val in vec[1:]:
47.         r.append(r[-1] + val)
48.     return r
49.
50. a=[1,2,3,4,5]
51. def cumsum(a):
52.     b=a[:]
53.     for i in range(1,len(a)):
54.         b[i]+=b[i-1]
55.     return b
56.
57. print cumsum(a)
58. "[1, 3, 6, 10, 15]"