Model pd.cut, which sorts numbers into labelled intervals, including its rules at the edges.
What to build
A program that bins values and counts each bin.
Requirements
- Edges e0 < e1 < ... define intervals labelled in order. By default (
right) a value x is in the interval (e_i, e_i+1]; withleftit is in [e_i, e_i+1). Withinclude_lowest(only meaningful with right), the first interval also holds e0. - A value in no interval is
NaN. Print each value's label in input order, thenLABEL: Cfor each label in order, thenNaN: C.
Input
Line 1: the edges. Line 2: the labels (one fewer than the edges). Line 3: right, left or right include_lowest. Line 4: the values.
Output
The labels, then the counts.
Constraints
2 to 10 edges; 1 to 100 values; all numbers are whole numbers.
Example
Input:
0 17 64 120
child adult senior
right
5 18 30 64 70 0
Output:
child
adult
adult
adult
senior
NaN
child: 1
adult: 3
senior: 1
NaN: 1
Why it works
Intervals that include only one edge never overlap, so every value lands in at most one bin; the cost is that the outermost edge on the open side belongs to no bin unless include_lowest says otherwise.
Examples
0 17 64 120 child adult senior right 5 18 30 64 70 0
child adult adult adult senior NaN child: 1 adult: 3 senior: 1 NaN: 1
0 17 64 120 child adult senior right include_lowest 0 17 120 121
child child senior NaN child: 2 adult: 0 senior: 1 NaN: 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
With right=True an interval (a, b] holds a < x <= b; with right=False, [a, b) holds a <= x < b.
Hint 2
include_lowest=True also lets the very first interval hold its left edge.
Solution
Show one correct solution (try it yourself first)
edges = list(map(int, input().split()))
labels = input().split()
mode = input().split()
values = list(map(int, input().split()))
right = mode[0] == "right"
lowest = "include_lowest" in mode
def bin_of(x):
for i in range(len(labels)):
a, b = edges[i], edges[i + 1]
if right and (a < x <= b or (lowest and i == 0 and x == a)):
return labels[i]
if not right and a <= x < b:
return labels[i]
return "NaN"
result = [bin_of(v) for v in values]
for r in result:
print(r)
for label in labels:
print(f"{label}: {result.count(label)}")
print(f"NaN: {result.count('NaN')}")