S2Q2 · Remainder Grouping Dictionary¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: group numbers by num % k, sort each group, print in sorted key order.
nums = [int(x.strip()) for x in input().split(",")]
k = int(input())
groups = {}
for n in nums:
r = n % k
if r not in groups:
groups[r] = []
groups[r].append(n)
for key in sorted(groups):
values = sorted(groups[key])
print(f"{key}-{','.join(map(str, values))}")
Key rules:
- Parse first line by splitting on ",", strip whitespace around each number
- Group by num % k
- Only include remainders that actually appear
- Print: key-val1,val2,... - no spaces around dash or commas
- Keys and values both in ascending order
Problem Statement¶
Problem (I/O type)
Read a comma-separated list of integers and a divisor k. Group numbers by their remainder mod k. Print each group sorted, in sorted key order, format key-val1,val2,....
Example:
10, 3, 7, 15, 2, 8, 21, 6
3
0-3,6,15,21
1-7,10
2-2,8
Tracing the example¶
Numbers: [10, 3, 7, 15, 2, 8, 21, 6], k=3
n |
n % 3 |
Group |
|---|---|---|
| 10 | 1 | → group 1 |
| 3 | 0 | → group 0 |
| 7 | 1 | → group 1 |
| 15 | 0 | → group 0 |
| 2 | 2 | → group 2 |
| 8 | 2 | → group 2 |
| 21 | 0 | → group 0 |
| 6 | 0 | → group 0 |
Groups (sorted values): {0: [3,6,15,21], 1: [7,10], 2: [2,8]}
Sorted keys → output as shown ✓
Solution approaches¶
line = input()
parts = line.split(",")
nums = []
for part in parts:
nums.append(int(part.strip()))
k = int(input())
groups = {}
for n in nums:
r = n % k
if r not in groups:
groups[r] = []
groups[r].append(n)
for key in sorted(groups):
sorted_vals = sorted(groups[key])
val_str = ",".join(str(v) for v in sorted_vals)
print(f"{key}-{val_str}")
Key takeaways¶
x.strip() handles spaces around commas
The input may have arbitrary spaces like "10, 3 , 7". Splitting on "," then stripping each part with .strip() cleanly handles any whitespace pattern before converting to int.
setdefault(r, []).append(n) for grouping
Initialises the list for new remainders and appends in one step. No if r not in groups check needed. Equivalent to defaultdict(list) but without the import.
','.join(map(str, sorted(...))) for the value format
Sort the group values, convert each to a string with map(str, ...), then join with no spaces using ",". The f-string f"{key}-{val_str}" produces the exact required format.