Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d8d55d1

Browse files
authored
Prepare private _rank() function to be made public. (#96372)
1 parent 675e347 commit d8d55d1

1 file changed

Lines changed: 15 additions & 5 deletions

File tree

Lib/statistics.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,8 @@ def _fail_neg(values, errmsg='negative value'):
355355
raise StatisticsError(errmsg)
356356
yield x
357357

358-
def _rank(data, /, *, key=None, reverse=False, ties='average') -> list[float]:
358+
359+
def _rank(data, /, *, key=None, reverse=False, ties='average', start=1) -> list[float]:
359360
"""Rank order a dataset. The lowest value has rank 1.
360361
361362
Ties are averaged so that equal values receive the same rank:
@@ -369,14 +370,22 @@ def _rank(data, /, *, key=None, reverse=False, ties='average') -> list[float]:
369370
>>> _rank([3.5, 5.0, 3.5, 2.0, 6.0, 1.0])
370371
[3.5, 5.0, 3.5, 2.0, 6.0, 1.0]
371372
372-
It is possible to rank the data in reverse order so that
373-
the highest value has rank 1. Also, a key-function can
374-
extract the field to be ranked:
373+
It is possible to rank the data in reverse order so that the
374+
highest value has rank 1. Also, a key-function can extract
375+
the field to be ranked:
375376
376377
>>> goals = [('eagles', 45), ('bears', 48), ('lions', 44)]
377378
>>> _rank(goals, key=itemgetter(1), reverse=True)
378379
[2.0, 1.0, 3.0]
379380
381+
Ranks are conventionally numbered starting from one; however,
382+
setting *start* to zero allow the ranks to be used as array indices:
383+
384+
>>> prize = ['Gold', 'Silver', 'Bronze', 'Certificate']
385+
>>> scores = [8.1, 7.3, 9.4, 8.3]
386+
>>> [prize[int(i)] for i in _rank(scores, start=0, reverse=True)]
387+
['Bronze', 'Certificate', 'Gold', 'Silver']
388+
380389
"""
381390
# If this function becomes public at some point, more thought
382391
# needs to be given to the signature. A list of ints is
@@ -389,7 +398,7 @@ def _rank(data, /, *, key=None, reverse=False, ties='average') -> list[float]:
389398
if key is not None:
390399
data = map(key, data)
391400
val_pos = sorted(zip(data, count()), reverse=reverse)
392-
i = 0 # To rank starting at 0 instead of 1, set i = -1.
401+
i = start - 1
393402
result = [0] * len(val_pos)
394403
for _, g in groupby(val_pos, key=itemgetter(0)):
395404
group = list(g)
@@ -400,6 +409,7 @@ def _rank(data, /, *, key=None, reverse=False, ties='average') -> list[float]:
400409
i += size
401410
return result
402411

412+
403413
def _integer_sqrt_of_frac_rto(n: int, m: int) -> int:
404414
"""Square root of n/m, rounded to the nearest integer using round-to-odd."""
405415
# Reference: https://www.lri.fr/~melquion/doc/05-imacs17_1-expose.pdf

0 commit comments

Comments
 (0)