Advertisement
here2share

# timeit_preserve_unique.py

Jan 21st, 2020
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1.  # timeit_preserve_unique.py
  2.  
  3. s = 'preserve unique'
  4.  
  5. from time import clock
  6.  
  7. t = sum([[3, 3, 3, 2, 2, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 4, 6, 5, 1, 5, 5, 5, 4, 5, 5, 4, 6, 5, 5, 6, 4, 4, 10, 10, 10, 5, 5, 10, 5, 11, 6, 10, 11, 6, 6, 11, 6, 11, 11, 10, 10, 10, 12, 1, 11, 10, 1, 12, 7, 3, 10, 4, 4, 4, 7, 1, 12, 12, 8, 4, 12, 12, 12, 11, 8, 4, 1, 7, 9, 7, 9, 9, 7, 8, 9, 7, 8, 8, 8, 0, 9, 0, 0, 7, 8, 7, 7, 1, 1, 1] for z in xrange(100)], [])
  8.  
  9. print '[3, 2, 1, 4, 5, 6, 10, 11, 12, 7, 8, 9, 0] ***'
  10.  
  11. def preserve_unique_a(items):
  12.     m = 'basic'
  13.     for i in xrange(len(items)-1, -1, -1):
  14.         x = items[i]
  15.         if x in items[:i]:
  16.             del items[i]
  17.     return items, m
  18.  
  19. def preserve_unique_b(items):
  20.     m = 'with set() [1 of 2]'
  21.     skip = set()
  22.     for i in xrange(len(items)-1, -1, -1):
  23.         x = items[i]
  24.         if x in skip:
  25.             del items[i]
  26.         elif x in items[:i]:
  27.             del items[i]
  28.         else:
  29.             skip.add(x)
  30.     return items, m
  31.  
  32. def preserve_unique_c(items):
  33.     m = 'with set() [2 of 2]'
  34.     skip = set()
  35.     pos = 0
  36.     for item in items:
  37.         if item not in skip:
  38.             skip.add(item)
  39.             items[pos] = item
  40.             pos += 1
  41.     del items[pos:]
  42.     return items, m
  43.  
  44. def preserve_unique_d(items):
  45.     m = 'with dict()'
  46.     skip = {}
  47.     pos = 0
  48.     for item in items:
  49.         if item not in skip:
  50.             skip[item] = True
  51.             items[pos] = item
  52.             pos += 1
  53.     del items[pos:]
  54.     return items, m
  55.  
  56. for fn in 'abcd':
  57.     test = 'preserve_unique_{}(%s)'.format(fn)
  58.     repeats = []
  59.     print
  60.     for tries in range(10):
  61.         z = t[:]
  62.         length = len(z)
  63.         #print len(z)
  64.         start = clock()
  65.         z,m = eval(test%(z))
  66.         stop = clock() - start
  67.         repeats += [stop]
  68.     print s, m
  69.     print 'length =', length
  70.     print z, 'best to {}: {:.5f}'.format(len(repeats), min(repeats))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement