| 1 | def clamp(x, lo=0, hi=100): |
| 2 | return max(lo, min(hi, x)) |
| 3 | |
| 4 | |
| 5 | def tally(rows): |
| 6 | counts = {} |
| 7 | for row in rows: |
| 8 | for field in row: |
| 9 | counts[field] = clamp(counts.get(field, 0) + 1) |
| 10 | return counts |
| 11 | |
| 12 | |
| 13 | def rebalance(counts): |
| 14 | total = sum(counts.values()) or 1 |
| 15 | return {k: v / total for k, v in counts.items()} |
| 16 |