2

I'm trying to write a version of cumulative sum in python using the reduce function. Here is my code so far:

from functools import reduce

def my_cum_sum(arg):
    return reduce(lambda a, x: (a.append(a[-1] + x)) if len(a) > 0 else a.append(x), arg, [])

assert(my_cum_sum([1, 1, 1, 1]) == [1, 2, 3, 4]))

But the problem is that in my lambda function, python doesn't know that a (my accumulator parameter) is a list object, and that I want my reduce function to return a list. In other functional programming languages, it might ask me to specify the type of a and x. But I'm new to python, and haven't quite figured out how it handles types and stuff. What is the pythonic way of solving this problem?

3 Answers 3

2

append returns None, so you cannot get the list back into reduce like this. Just use the addition between the list and a list made of a single element, or just a list made of initial element if list is empty:

from functools import reduce

def my_cum_sum(arg):
    return reduce(lambda a, x: a + [a[-1]+x] if a else [x], arg, [])

print (my_cum_sum([1, 1, 1, 1]))

result:

[1, 2, 3, 4]

(note that if len(a)>0 is better written if a as well)

Sign up to request clarification or add additional context in comments.

4 Comments

Why do you use a[-1]?
this is the current last element of a
But isn't "a" already a single element?
no it's the parameter of the lambda passed by reduce so it's a list. Try it out
0

Why not use Python's accumulate (although this doesn't explicitly use reduce)?

from itertools import accumulate

def my_cum_sum(arg) -> list:
  result = accumulate(arg)
  return list(result)

assert(my_cum_sum([1, 1, 1, 1]) == [1, 2, 3, 4])

Comments

0

You can make the lambda do the append and then return the list.

from functools import reduce

def my_cum_sum(arg):
    return reduce(lambda a, x: a.append(a[-1] + x if a else x) or a, arg, [])

assert(my_cum_sum([1, 1, 1, 1]) == [1, 2, 3, 4])

Attempt This Online!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.