2

I am using numpy arrays in my codes very frequently. Its speed and convenient indexing rules are very useful. Now, I am searching how to avoid 'for' loops in order to make execution time faster. For the simplicity, let's assume that, we have two vectors(named a and b), each has 10 elements. First value of second vector(b) is equal to 1, then each nth value is equal to '(b[n-1]*13+a[n])/14'. With the help of 'for' loop, I can write that like below:

import numpy as np
a = np.random.random(10)
b = np.ones(10)
for i in range(1, b.shape[0]):
    b[i] = (b[i-1]*13 + a[i]) / 14

So, my question is how can I do same thing without for loop and faster? How can I use numpy vectorization to do that operation? Thanks in advance!

5

1 Answer 1

-3

Few days ago I was asked same question in an interview ,so I came up with my implementation in java.I used recursion to iterate over an array

public class IterateWithoutLoop {

private int[]arr;
int size;


public IterateWithoutLoop(int[] arr) {      
    this.arr = arr;
    this.size = 0;
}


public static void main(String[] args) {
    int[]arr={1,2,3,4,5};
    int i=0;
    IterateWithoutLoop iterator=new IterateWithoutLoop(arr);
    iterator.iterateOverArray();
}
public void iterateOverArray(){
    if(arr.length!=size){

        System.out.print(arr[size++]+"\t");
        iterateOverArray();         
    }

}

}

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

1 Comment

Although this would be useful on a Java question, your answer is not helpful here because there is virtually no similarity between a numpy solution to this problem and a java solution.

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.