Pythonic way to iterate through multidimensional space?

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Aug 6 03:33:20 EDT 2014


On 06/08/2014 06:34, Gayathri J wrote:
> Dear Peter
>
> Below is the code I tried to check if itertools.product() was faster
> than normal nested loops...
>
> they arent! arent they supposed to be...or am i making a mistake? any idea?
> *
> *
> *############################################################
> *
> *# -*- coding: utf-8 -*-
> *
> *import numpy as np*
> *import time*
> *from itertools import product,repeat*
> *def main():*
> *    # N - size of grid*
> *    # nvel - number of velocities*
> *    # times - number of times to run the functions*
> *    N=256*
> *    times=3*
> *    f=np.random.rand(N,N,N)*
> **
> *    # using loops*
> *    print "normal nested loop"*
> *    python_dot_loop1(f,times,N)*
> *
> *
> *    print "nested loop using itertools.product()"*
> *    python_dot_loop2(f,times,N)*
> *
> *
> *def python_dot_loop1(f,times,N):*
> *    for t in range(times):*
> *         t1=time.time()*
> *         for i in range(N):*
> *             for j in range(N):*
> *                   for k in range(N):*
> *                       f[i,j,k] = 0.0*
> *         print "python dot loop " + str(time.time()-t1)*
> **
> *def python_dot_loop2(f,times,N):*
> *    rangeN=range(N)*
> *    for t in range(times):*
> *         t1=time.time()*
> *         for i,j,k in product(rangeN,repeat=3):*
> *             f[i,j,k]=0.0*
> *         print "python dot loop " + str(time.time()-t1)*
> *
> *
> *
> *
> *if __name__=='__main__':*
> *    main()*
> *############################################################*
>
>

Who cares, well not I for one?  Give me slower but accurate code over 
faster but inaccurate code any day of the week?

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list