Skip to content

Instantly share code, notes, and snippets.

@volf52
Created September 5, 2017 08:33
Show Gist options
  • Save volf52/123292713c413e6626e92283b365d68a to your computer and use it in GitHub Desktop.
Save volf52/123292713c413e6626e92283b365d68a to your computer and use it in GitHub Desktop.
Spearman's Rank Correlation Coefficient (Unique Data Sets) - Python
def main():
n = int(raw_input().strip())
X = map(float, raw_input().strip().split(' '))
Y = map(float, raw_input().strip().split(' '))
x_rank = ranking(X)
y_rank = ranking(Y)
d_sq = [(x-y)**2 for x,y in zip(x_rank, y_rank)]
print round(1-((6.0*sum(d_sq))/(n*(n**2 - 1))), 3)
def ranking(arr):
cp = []
for x in arr:
if cp.count(x) == 0:
cp.append(x)
cp.sort()
ranks = {x:y for x,y in zip(cp, range(1, len(cp)+1))}
return [ranks[x] for x in arr]
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment