infamouswhiteknight
infamouswhiteknight

Reputation: 23

Python: How can I add a parameter to an itertools function?

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

Upvotes: 2

Views: 212

Answers (1)

Mustafa Aydın
Mustafa Aydın

Reputation: 18315

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.

Upvotes: 2

Related Questions