Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if __name__ == '__main__':
- import timeit
- tries = 1000000
- tests = [
- 'def count_capitals(word):return sum([1 for _ in word if _.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
- 'def count_capitals(word):return len([1 for _ in word if _.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
- 'def count_capitals(word):return len([_ for _ in word if _.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
- 'def count_capitals(word):return len([c for c in word if c.isupper()]);count_capitals("string.ascii_uppercase * 1000000")',
- 'def count_capitals(word):return sum(_.isupper() for _ in word);count_capitals("string.ascii_uppercase * 1000000")',
- 'def count_capitals(word):return sum(map(str.isupper, s));count_capitals("string.ascii_uppercase * 1000000")',
- ]
- for test in tests:
- r = timeit.timeit(test, number=tries)
- test = test.replace('def count_capitals(word):return ', '')
- print(f"{test[:test.index(';')]:<40s}{r}")
- # sum([1 for _ in word if _.isupper()]) 0.25757529999999984
- # len([1 for _ in word if _.isupper()]) 0.20968720000000007
- # len([_ for _ in word if _.isupper()]) 0.15788329999999995
- # len([c for c in word if c.isupper()]) 0.1378284999999999
- # sum(_.isupper() for _ in word) 0.15373329999999985
- # sum(map(str.isupper, s)) 0.1981145999999998
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement