Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Aug 2nd, 2013  |  syntax: Python  |  size: 1.83 KB  |  views: 25  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import functools
  2. import random
  3. import sys
  4. import timeit
  5.  
  6. if sys.version_info < (3, 0):
  7.     range = xrange
  8.  
  9. def revind(L, n):
  10.     indices = [index for index, item in enumerate(L) if item==n]
  11.     for index in reversed(indices):
  12.         del L[index]
  13.  
  14. def whiledel(L, n):
  15.     i = 0
  16.     while i < len(L):
  17.         if L[i] == n:
  18.             del L[i] # Do not increment i here, because L[i] will change
  19.         else:
  20.             i += 1
  21.        
  22. def slide(L, n):
  23.     # indices takes *worse-case* O(N) space, but typical-case much less
  24.     indices = [i for i, x in enumerate(L) if x==n]
  25.     indices_seen = 0
  26.     num_indices = len(indices)
  27.     for i in range(len(L)):
  28.         if (indices_seen < num_indices and
  29.             i + indices_seen == indices[indices_seen]):
  30.             indices_seen += 1
  31.         if i+indices_seen >= len(L):
  32.             break
  33.         L[i] = L[i+indices_seen]            
  34.     L[-indices_seen:] = []
  35.  
  36. def genexpr(L, n):
  37.     L[:] = (i for i in L if i != n)
  38.  
  39. def listcomp(L, n):
  40.     L[:] = [i for i in L if i != n]
  41.  
  42. if sys.version_info < (3, 0):
  43.     def filterer(L, n):
  44.         L[:] = filter(lambda i: i != n, L)
  45. else:
  46.     def filterer(L, n):
  47.         L[:] = filter(n.__ne__, L)
  48.  
  49. def remove(L, n):
  50.     while True:
  51.         try:
  52.             L.remove(n)
  53.         except ValueError:
  54.             break
  55.  
  56. def removein(L, n):
  57.     while n in L:
  58.         L.remove(n)
  59.  
  60. maxnum = int(sys.argv[1]) if len(sys.argv) > 1 else 16
  61. listlen = int(sys.argv[2]) if len(sys.argv) > 2 else 1000000
  62. reps = int(sys.argv[3]) if len(sys.argv) > 3 else 3
  63.  
  64. L0 = [random.randrange(maxnum) for _ in range(listlen)]
  65. for f in revind, whiledel, slide, genexpr, listcomp, filterer, remove, removein:
  66.     L = L0[:]
  67.     p = functools.partial(f, L, 0)
  68.     print('{}: {} ({})'.format(f.__name__, timeit.timeit(p, number=reps), len(L)))