2

I want to create a function which returns a function creating an iterator (like something from itertools), but with a parameter set by the outer function.

For example, say I want to take a running sum, but exclude values that are larger than a given cutoff (which is the parameter of the function).

So, say I have a list like this:

x = [1, 1, 1, 1, 25, 1, 1]

And I want a function that would take the running sum, but ignore values greater than 10, to give me an output like this:

y = [1, 2, 3, 4, 4, 5, 6]

This code will do the trick:

t = 10
accumulate(x,lambda x,y:x if y>=t else x+y)

But now I want to make a function which returns a function like the above, where I can pass it the value t as the parameter. This is what I tried:

def sum_small_nums(t):
    def F(x):
        new_x = accumulate(x,lambda x,y: x if y>=t else x+y)
    return F

Unfortunately this doesn't seem to work. I can create a function from the above, but when I try to call it, I don't get the output I am expecting (e.g. I get 'None' instead of a list):

sum_under_10 = sum_small_nums(10)
print(sum_under_10)
x = [1, 1, 1, 1, 25, 1, 1]
x2 = sum_under_10(x)
print(x2)

returns

<function sum_small_nums.<locals>.F at 0x7feab135a1f0>
None
2
  • Do you intend that if the first element is over 25, the accumulator starts at that value instead of zero? Commented Mar 29, 2021 at 20:36
  • @kaya3 good point, though it's not so relevant to me in this case, as this was a simplified example. The 'initial' argument of accumulate should solve that if necessary I think. The answer below solved my real problem. Commented Mar 30, 2021 at 12:57

1 Answer 1

2

You're close! Need to return the list from the inner function:

def sum_small_nums(t):
    def F(x):
        new_x = accumulate(x, lambda x, y: x if y >= t else x + y)
        return list(new_x)
   return F

When you don't return anything from a function, None is implicitly returned.

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

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.