Created
December 30, 2011 00:34
-
-
Save rmax/1536931 to your computer and use it in GitHub Desktop.
non-pythonic vs pythonic code
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
from __future__ import division | |
def c_avrg(the_dict, exclude): | |
""" Calculate the average excluding the given element""" | |
i = 0 | |
total = 0 | |
for e in the_dict: | |
if e != exclude: | |
i += 1 | |
total += the_dict[e] | |
if i>0: return float(total/i) | |
else: return 0 |
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
from __future__ import division | |
def c_avrg(the_dict, exclude): | |
""" Calculate the average excluding the given element | |
>>> c_avrg({'foo': 80, 'bar': 100, 'for': 99}, 'bar') | |
89.5 | |
>>> c_avrg({'foo': 100}, 'foo') | |
0 | |
""" | |
values = [v for (k, v) in the_dict.iteritems() if k != exclude] | |
if values: | |
return sum(values) / len(values) | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An improvement : https://gist.github.com/1537032 :)