Advertisement
Guest User

Untitled

a guest
Nov 10th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1.  
  2. if __name__ == '__main__':
  3.     import timeit
  4.  
  5.     tries = 1000000
  6.     tests = [
  7.         'def count_capitals(word):return sum([1 for _ in word if _.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
  8.         'def count_capitals(word):return len([1 for _ in word if _.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
  9.         'def count_capitals(word):return len([_ for _ in word if _.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
  10.         'def count_capitals(word):return len([c for c in word if c.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
  11.         'def count_capitals(word):return sum(_.isupper() for _ in word);count_capitals("string.ascii_uppercase * 1000000")',
  12.         'def count_capitals(word):return sum(map(str.isupper, s));count_capitals("string.ascii_uppercase * 1000000")',
  13.     ]
  14.  
  15.     for test in tests:
  16.         r = timeit.timeit(test, number=tries)
  17.         test = test.replace('def count_capitals(word):return ', '')
  18.         print(f"{test[:test.index(';')]:<40s}{r}")
  19.  
  20. # sum([1 for _ in word if _.isupper()])   0.25757529999999984
  21. # len([1 for _ in word if _.isupper()])   0.20968720000000007
  22. # len([_ for _ in word if _.isupper()])   0.15788329999999995
  23. # len([c for c in word if c.isupper()])   0.1378284999999999
  24. # sum(_.isupper() for _ in word)          0.15373329999999985
  25. # sum(map(str.isupper, s))                0.1981145999999998
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement