Skip to content

Instantly share code, notes, and snippets.

@andrix
Forked from rmax/avg.orig.py
Created December 30, 2011 01:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrix/1537032 to your computer and use it in GitHub Desktop.
Save andrix/1537032 to your computer and use it in GitHub Desktop.
pythonic vs non-pythonic code
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
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
@seanjohnson08
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment