Friday, July 8, 2011

A beginning Python programming challenge: replace slow array.index() calls.


For simplicity, consider the following arrays:



i      0  1   2 3  4  5  6  7  8  9  10
order1 6  9   7 10  5  8 3  2  4   0   1
order2 7  6  10  8  5  9 1  4  2   0   3


Now consider the following Python snippet of code:


myindex = range(11)

for i in range(11):

    myindex[i] = order2[order1.index[i]]



As an example consider a current i value of 0. The value of index1[0] is 6. The position of 6 in order2 is of 6 in index2 array is 1(first element has index0). Therefore myindex[0] = 1.

On the other hand, the value of index1[1] is 9. The ordinal position of 9 in index2 is 5. Hence myindex[1] = 5.

Problem 1. Can you replace the code without using dictionaries and the index function?
You may not modify inplace the order1 and order2 arrays. You may create an additional extra array.

Problem 2.  Rewrite the code to use a dictionary. This is much easier.

Imagine your are doing the for loop of 1,000,000 array items! Have fun!

No comments:

Post a Comment