0

I have a list in which total number of items may change. I want to apply a function which requires two inputs on first two items in the list and with the result I want to apply the same function on the third item in the list and with the result I want to apply function for fourth and so on...

Is there a better way to do the below when you know number of items in the list

for x,y,a,b,c...n in result:
    z=np.convolve(x,y)
    z=np.convolve(z,a)
    z=np.convolve(z,b)
    z=np.convolve(z,c)
    .
    .
    .
    final=np.convolve(z,n)
print(final)
Moca
  • 25
  • 1
  • 4

2 Answers2

2

What you want to do is called reduce-function. Python has them.

For your case, you can use them like this:

from functools import reduce

reduce(lambda x, y: np.convolve(x, y), result)
vurmux
  • 9,420
  • 3
  • 25
  • 45
  • Upvoted, but note that you should always include an initializer value for the reduce function, including here. – Kenan Banks May 07 '19 at 16:56
  • No, it is optional. In the case of OP's question the behaviour is exactly equal to his expectations: `If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.` – vurmux May 07 '19 at 17:00
  • Great, but how does this handle an empty list? You can get away with leaving out an initializer _sometimes_, but providing one makes for clearer code and, importantly, keeps you from breaking out of your monoid. – Kenan Banks May 07 '19 at 17:03
  • In the case of the empty iterator it will crash. But does OP has empty iterator? Anyway, we don't know what he has in the `result`. – vurmux May 07 '19 at 17:07
  • The length is variable, per the OP. No reason to think it's always non-zero length. – Kenan Banks May 07 '19 at 17:07
-1

You can do this:

for args in result:
    x, y, *others = args
    z = np.convolve(x,y)

    for a in others:
        z = np.convolve(z,a)
ForceBru
  • 43,482
  • 10
  • 63
  • 98