Return the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5]) 3 >>> medi
(data)
| 547 | |
| 548 | # FIXME: investigate ways to calculate medians without sorting? Quickselect? |
| 549 | def median(data): |
| 550 | """Return the median (middle value) of numeric data. |
| 551 | |
| 552 | When the number of data points is odd, return the middle data point. |
| 553 | When the number of data points is even, the median is interpolated by |
| 554 | taking the average of the two middle values: |
| 555 | |
| 556 | >>> median([1, 3, 5]) |
| 557 | 3 |
| 558 | >>> median([1, 3, 5, 7]) |
| 559 | 4.0 |
| 560 | |
| 561 | """ |
| 562 | data = sorted(data) |
| 563 | n = len(data) |
| 564 | if n == 0: |
| 565 | raise StatisticsError("no median for empty data") |
| 566 | if n % 2 == 1: |
| 567 | return data[n // 2] |
| 568 | else: |
| 569 | i = n // 2 |
| 570 | return (data[i - 1] + data[i]) / 2 |
| 571 | |
| 572 | |
| 573 | def median_low(data): |
nothing calls this directly
no test coverage detected