Advertisement
Guest User

Faster in Python 2 than Python 3 - why?

a guest
Sep 22nd, 2011
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. def dump(a):
  2.     # print("Array: ",",".join((str(i) for i in a)));
  3.     pass
  4.  
  5. swaps=0
  6. def swap(a,i,j):
  7.     global swaps
  8.     tmp=a[i]; a[i]=a[j]; a[j]=tmp;
  9.     # print("Swap:  "+"   "*i+"^^ "+"   "*(j-i-1)+"^^\n");
  10.     swaps+=1;
  11.  
  12. import random
  13. import time
  14. sz=1000000; top=sz*10-1
  15. start=time.time();
  16. # a=[random.randint(0,top) for i in range(sz)]
  17. a=[int(random.random()*top) for i in range(sz)]
  18. # a=[6,5,3,1,8,7,2,4]
  19. print("Build array: ",time.time()-start)
  20.  
  21. dump(a);
  22. start=time.time();
  23. # Build the heap
  24. for i in range(len(a)):
  25.     # dump(a);
  26.     # print("Ins:   "+"   "*i+"^^")
  27.     x=i;
  28.     j=(i-1)//2;
  29.     while (j>0):
  30.         # print("Cmp:   "+"   "*j+"^^\n");
  31.         if (a[x]>a[j]): swap(a,j,x); x=j
  32.         j=(j-1)//2
  33.     if (a[x]>a[0]): swap(a,0,x);
  34. print("--- Heap built (%d swaps) ---"%swaps);
  35. dump(a);
  36.  
  37. top=len(a);
  38. while (top>1):
  39.     # print("Remove %d from heap"%a[0]);
  40.     top-=1
  41.     swap(a,0,top);
  42.     par=0;
  43.     child=par*2+1;
  44.     while (child<top):
  45.         swapme=par;
  46.         # print("Cmp:   "+"   "*par+"^^ "+"   "*(child-par-1)+"^^ ^^");
  47.         if (a[child]>a[par]): swapme=child;
  48.         if (child<top-1 and a[child+1]>a[swapme]): swapme=child+1;
  49.         if (swapme==par): break; # Parent already greater than both children
  50.         swap(a,par,swapme);
  51.         # dump(a);
  52.         par=swapme;
  53.         child=par*2+1;
  54. print("--- Array sorted in %d swaps total ---"%swaps);
  55. print("Total time: ",time.time()-start);
  56. dump(a);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement