Mercurial > hg > medcouple
changeset 31:1a2bb52722c2
pymedcouple: replace slow Python partsort with faster built-in full sort
author | Jordi Gutiérrez Hermoso <jordigh@octave.org> |
---|---|
date | Sun, 18 Jan 2015 20:45:35 -0500 |
parents | 2e277129e81b |
children | 5b77348383b7 |
files | pymedcouple |
diffstat | 1 files changed, 4 insertions(+), 34 deletions(-) [+] |
line wrap: on
line diff
--- a/pymedcouple +++ b/pymedcouple @@ -4,38 +4,6 @@ from itertools import tee, izip - -def partsort(L, n): - """This is a partial sort of the weighted list L = [(a,w) for a in A, - w in W], so that the element at position n is in the correct spot. - Also known as quickselect. The elements of W are ignored for the - purposes of this partial sort. - """ - - beg = 0 - end = len(L) - - while True: - pivot = random.randint(beg, end - 1) - pivotval = L[pivot][0] - L[pivot], L[end - 1] = L[end - 1], L[pivot] - - idx = beg - for i in xrange(beg, end): - if L[i][0] < pivotval: - L[idx], L[i] = L[i], L[idx] - idx += 1 - - L[idx], L[end-1] = L[end-1], L[idx] - - if idx == n: - return L[idx] - elif idx < n: - beg = idx + 1 - else: - end = idx - - def wmedian(A, W): """This computes the weighted median of array A with corresponding weights W. @@ -52,7 +20,8 @@ while True: mid = (beg + end)//2 - partsort(AW, mid) + AW = sorted(AW, key = lambda x: x[0]) # A partial sort would suffice here + trial = AW[mid][0] wleft = wright = 0 @@ -212,7 +181,8 @@ for (i, (l, r)) in enumerate(izip(L, R)): for j in xrange(l, r + 1): A.append(h_kern(i, j)) - A.sort() + + A.sort() # A partial sort would suffice here A.reverse() Am = A[medc_idx - Ltot]