-
-
Save andrix/1537032 to your computer and use it in GitHub Desktop.
pythonic vs non-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] | |
return sum(values) / len(values) if values else 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def c_avrg(the_dict,exclude):
""" Calculate the average excluding the given element"""
the_dict=the_dict.copy()
if(exclude in the_dict) del the_dict[exclude]
return sum(the_dict.values())/len(the_dict)