1

So I would like to iterate over two lists simultaneously and I also need the index as done with the following code. Both are straightforward to me, but is it possible two use enumerate in the second case as well? Of course, assuming both var arrays are of the same length.

import numpy as np

def _eqn(y, variables, sign=-1.0):
    f = 0
    for i,x in enumerate(variables):
        f += x/(1+0.06)**(i+1)
    return float(sign*(y + f))


_eqn(1,np.array([1,1]))

def _eqn2(y, vars1, vars2, sign=-1.0):
    f = 0
    n = len(vars1)
    for x,y,i in zip(vars1, vars2, range(n)):
        f += (x+y)/(1+0.06)**(i+1)
    return float(sign*(y + f))


_eqn2(1,np.array([1,1]),np.array([1,1]))
1
  • Did you try it? Commented Nov 17, 2017 at 13:07

1 Answer 1

5

Yes, it is possible... although with a slight change

def _eqn2(y, vars1, vars2, sign=-1.0):
    f = 0
    for i, (v1,v2) in enumerate(zip(vars1, vars2)):
        f += (v1+v2)/(1+0.06)**(i+1)
    return float(sign*(y + f))

You enumerate tuples of the zip of your vars.

Although since you're working with numpy arrays, I'm sure that there is a better way to achieve this same goal without using a python for loop.

Also took the liberty of changing the names of variables since you were usign y in two different contexts and could be confusing.

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

4 Comments

Ok, can you give a hint solving this without a for loop?
You make an array of numerators and another one of denominators (a**b in numpy works as element-wise exponentiation) and then you divide numerator by denominator which is also a vectorized operation and in the end you do a sum of that array. That will eliminate the whole for loop. Eventually if your lists/arrays are big enough it can be performance-worthy.
You are right, that this can easily be achieved with vectorized operations. And indeed it gets faster with bigger arrays. You think this is the best way? f = ((vars1+vars2)/(1+0.06)**(np.arange(len(vars1))+1)).sum()
That looks like what I would have done. You can explicitly ass 1 with 0.06 to avoid one addition.

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.