jasmine
jasmine

Reputation: 9

Need to create a function cumsum that returns the cumulative sum of a list l

Full instructions: Write a function cumsum that takes a list l as argument and returns the cumulative sum (also known as the prefix sum) of l, which is a list, say cs of the same length as l such that each element cs[i] is equal to the sum of the first i + 1 elements of l,

I have this so far but Im not sure where Im going wrong as it keeps failing all the tests.

**Also cannot assume a certain data type in the list (can be strings, integers, etc.) How would I initialize this so it can work for any data type

My code so far:

def cumsum(l):

  cs = []

  total = 0

  for x in range(l):

    total = total + x

    cs.append(total)

  return cs

(Note: I cannot use any imports or extra tools, supposed to use the append function) Does anyone know what I can do to get this to work?

Upvotes: 0

Views: 1209

Answers (2)

Stefan
Stefan

Reputation: 632

If you can assume that all elements are of the same type, this works for numbers and string:

def cumsum(l):
  cs = []
  total = None
  for x in l:
    if total is None:
        total=x
    else:
        total = total + x
    cs.append(total)
  return cs

print(cumsum([1,2,3]))

Upvotes: 0

Stoobish
Stoobish

Reputation: 1382

Adding on to Muhammad's answer, type cast x to int

def cumsum(l):    
  cs = []    
  total = 0    
  for x in l:    
    total = total + int(x)
    cs.append(total)
  return cs

Upvotes: 1

Related Questions