Guest User

Untitled

a guest
Dec 19th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. def count1(words):
  3. c = {}
  4. for w in words:
  5. if w in c:
  6. c[w] += 1
  7. else:
  8. c[w] = 1
  9. return c
  10.  
  11.  
  12. def count2(words):
  13. c = {}
  14. for w in words:
  15. try:
  16. c[w] += 1
  17. except KeyError:
  18. c[w] = 1
  19. return c
  20.  
  21.  
  22.  
  23. test1 = """
  24. The implementation of Python sets derive from the dictionary implementation. Indeed, there is some evidence that originally the implementation was mostly a copy-paste from the dict implementation.
  25.  
  26. Python sets are implemented as dictionaries with dummy values (i.e. the keys are the members of the set) and there are optimizations for cache locality which take advantage of this lack of values. Thus, sets membership is done in O(1) as in dictionaries. Note that in the worst case (i.e. all hash collisions) the membership-checking is O(n).
  27.  
  28. Because of this amazingly fast membership checking, sets are the obvious choice when you have a list of values and you don’t care about the order of the items, but just whether an item belongs to the list or not. Of course this is true only if the set is already there. If you include the set creation time, then a list is usually faster, as the following experiment shows
  29. """
  30. test1 = list(filter(None, test1.strip().split()))
  31.  
  32.  
  33. test2 = ("foo bar baaz" * (len(test1) // 3)).split()
  34.  
  35.  
  36. import timeit
  37.  
  38. n = 10000
  39.  
  40. print("count1, test1")
  41. print(timeit.timeit("count(test)", "from __main__ import count1 as count, test1 as test", number=n))
  42. print("count1, test2")
  43. print(timeit.timeit("count(test)", "from __main__ import count1 as count, test2 as test", number=n))
  44. print("count2, test1")
  45. print(timeit.timeit("count(test)", "from __main__ import count2 as count, test1 as test", number=n))
  46. print("count2, test2")
  47. print(timeit.timeit("count(test)", "from __main__ import count2 as count, test2 as test", number=n))
Add Comment
Please, Sign In to add comment