-
-
Save mtigas/8bfbf6bce03e55f68c56 to your computer and use it in GitHub Desktop.
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 gini(population): | |
""" | |
https://en.wikipedia.org/wiki/Gini_coefficient#Calculation | |
see "This may be simplified to:" | |
""" | |
pop = sorted(population) | |
n = len(pop) | |
a = 0 | |
for idx, item in enumerate(pop, 1): | |
a += (idx * item) | |
a *= 2 | |
b = 0 | |
for item in pop: | |
b += n * item | |
return (a / b) - (n+1)/n | |
def gini2(population): | |
""" | |
https://en.wikipedia.org/wiki/Gini_coefficient#Calculation | |
see "This may be simplified to:" | |
(as above, but using reduce (with "initial=0" as accumulator) | |
""" | |
pop = sorted(population) | |
n = len(pop) | |
a = 2 * reduce( | |
lambda prev, (idx, item): prev + (idx * item), | |
enumerate(pop, 1), | |
0 | |
) | |
b = reduce( | |
lambda prev, item: prev + (n * item), | |
pop, | |
0 | |
) | |
return (a / b) - (n+1)/n | |
def gini3(population): | |
""" | |
https://en.wikipedia.org/wiki/Gini_coefficient#Calculation | |
see "This may be simplified to:" | |
(as above, but basically doing map then reduce | |
""" | |
pop = sorted(population) | |
n = len(pop) | |
a = 2 * sum(map( | |
lambda (idx, item): idx * item, | |
enumerate(pop, 1) | |
)) | |
b = sum(map( | |
lambda item: n * item, | |
pop | |
)) | |
return (a / b) - (n+1)/n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment