Guest User

Untitled

a guest
Apr 26th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. """
  2. The following is an attempt to gather various useful usecases of
  3. collections.Counter in python. Some were once contributed to
  4. Stackoverflow Documentation Experiment but since its shut down
  5. I could not recover them.
  6. """
  7.  
  8. # imports
  9. from collections import Counter
  10. import random
  11.  
  12. # Construct Counter
  13.  
  14. ## Empty Counter
  15. c = Counter() # Counter()
  16.  
  17. ## From list
  18. c = Counter(['a', 'b', 'a', 'c']) # Counter({'a': 2, 'b': 1, 'c': 1})
  19. c = Counter('abac') # Counter({'a': 2, 'b': 1, 'c': 1})
  20.  
  21. ## From dictionary
  22. c = Counter({'a': 2, 'b': 1, 'c': 1}) # Counter({'a': 2, 'b': 1, 'c': 1})
  23.  
  24. # Modify Counter
  25.  
  26. ## Add elements
  27. c = Counter(['b'])
  28. c['a'] += 1 # Counter({'a': 1, 'b': 1})
  29. c.update(['a']) # Counter({'a': 2, 'b': 1})
  30. c.update(['a', 'b', 'c']) # Counter({'a': 3, 'b': 2, 'c': 1})
  31. c['c'] += 3 # Counter({'a': 3, 'b': 2, 'c': 4})
  32.  
  33. ## Remove elements
  34. c['c'] -= 2 # Counter({'a': 3, 'b': 2, 'c': 2})
  35. c['b'] = 0 # Counter({'a': 3, 'b': 0, 'c': 2})
  36. c.subtract('a'*4) # Counter({'a': -1, 'b': 0, 'c': 2})
  37.  
  38. ## Delete elements
  39. c += Counter() # Counter({'c': 2}) - remove zero and negative counts
  40. #! Adding or subtracting any counter will have the same effect
  41. del c['c'] # Counter()
  42.  
  43. # Counting
  44. ## Simple access
  45. c = Counter(a=4, b=2, c=0, d=-2)
  46. c['a'] # 4
  47. c['e'] # 0 (missing element)
  48. ## Access 3 most common
  49. c.most_common(3) # [('a', 4), ('b', 2), ('c', 0)]
  50. ## Access 3 least common
  51. c.most_common()[:-3-1:-1] # [('d', -2), ('c', 0), ('b', 2)]
  52.  
  53. # Sampling (not necessarily optimal)
  54. ## Sample elements (ignores 0 and negative)
  55. c = Counter(a=4, b=2, c=0, d=-2)
  56. els = list(c.elements()) # ['a', 'a', 'a', 'a', 'b', 'b']
  57. random.choice(els)
  58. random.sample(els, 6)
  59.  
  60. ## Sample keys
  61. c = Counter(a=4, b=2, c=0, d=-2)
  62. random.choice(list(c.keys()))
  63. random.sample(c.keys(), 4)
  64.  
  65. ## Sample positive keys
  66. random.choice([x for x in c if c[x]>0])
  67. random.sample([x for x in c if c[x]>0], 2)
  68.  
  69. ## Sample one of the least common positive keys
  70. (c + Counter()).most_common()[-1][0]
Add Comment
Please, Sign In to add comment