Skip to content

Instantly share code, notes, and snippets.

@rmax
Created December 30, 2011 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmax/1536931 to your computer and use it in GitHub Desktop.
Save rmax/1536931 to your computer and use it in GitHub Desktop.
non-pythonic vs 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]
if values:
return sum(values) / len(values)
return 0
@andrix
Copy link

andrix commented Dec 30, 2011

An improvement : https://gist.github.com/1537032 :)

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