Created
December 18, 2014 14:05
-
-
Save BrianHicks/95f9380d0d5e9b5024b5 to your computer and use it in GitHub Desktop.
averages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Python 2.7.8 (default, Nov 14 2014, 15:57:55) | |
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin | |
Type "help", "copyright", "credits" or "license" for more information. | |
>>> def avg1(nums): | |
... return sum(nums) / float(len(nums)) | |
... | |
>>> def avg2(nums): | |
... count, tot = 0, 0 | |
... for num in nums: | |
... count += 1 | |
... tot += num | |
... return tot / float(count) | |
... | |
>>> avg1(range(100)) | |
49.5 | |
>>> avg2(range(100)) | |
49.5 | |
>>> from timeit import timeit | |
>>> timeit('avg1(range(100))', 'from __main__ import *') | |
2.8819470405578613 | |
>>> timeit('avg2(range(100))', 'from __main__ import *') | |
14.88791298866272 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Python 2.7.8 (f5dcc2477b97, Sep 19 2014, 18:09:54) | |
[PyPy 2.4.0 with GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin | |
Type "help", "copyright", "credits" or "license" for more information. | |
>>>> def avg1(nums): | |
.... return sum(nums) / float(len(nums)) | |
.... | |
>>>> def avg2(nums): | |
.... count, tot = 0, 0 | |
.... for num in nums: | |
.... count += 1 | |
.... tot += num | |
.... return tot / float(count) | |
.... | |
>>>> avg1(range(100)) | |
49.5 | |
>>>> avg2(range(100)) | |
49.5 | |
>>>> from timeit import timeit | |
>>>> timeit('avg1(range(100))', 'from __main__ import *') | |
0.27321791648864746 | |
>>>> timeit('avg2(range(100))', 'from __main__ import *') | |
0.2980170249938965 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment