fork download
  1. # cumulative_sum.py
  2. # MIT OCW 6.189 A Gentle Introduction to Programming Using Python
  3. # Homework 2 > Exercise 2.7 Working With Lists > cumulative_sum
  4. # Glenn Richard
  5. # July 5, 2013
  6.  
  7. def cumulative_sum(number_list):
  8. # number_list is a list of numbers
  9. c_sum = 0
  10. c_sum_list = []
  11. for number in number_list:
  12. c_sum += number
  13. c_sum_list.append(c_sum)
  14. return c_sum_list
  15.  
  16. def cumulative_sum_list_comp(number_list):
  17. # number_list is a list of numbers
  18. return [sum(number_list[:i + 1]) for i in range(len(number_list))]
  19.  
  20. # Test Cases
  21. print "cumulative_sum([1, 2, 3, 4]) is:", cumulative_sum([1, 2, 3, 4])
  22. print "cumulative_sum_list_comp([1, 2, 3, 4]) is:", cumulative_sum_list_comp([1, 2, 3, 4])
  23. print "cumulative_sum([1, 1, 2, 3, 5, 8]) is:",cumulative_sum([1, 1, 2, 3, 5, 8])
  24. print "cumulative_sum_list_comp([1, 1, 2, 3, 5, 8]) is:",cumulative_sum_list_comp([1, 1, 2, 3, 5, 8])
  25.  
Success #stdin #stdout 0.01s 7728KB
stdin
Standard input is empty
stdout
cumulative_sum([1, 2, 3, 4]) is: [1, 3, 6, 10]
cumulative_sum_list_comp([1, 2, 3, 4]) is: [1, 3, 6, 10]
cumulative_sum([1, 1, 2, 3, 5, 8]) is: [1, 2, 4, 7, 12, 20]
cumulative_sum_list_comp([1, 1, 2, 3, 5, 8]) is: [1, 2, 4, 7, 12, 20]