-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
40 lines (32 loc) · 1.41 KB
/
Copy pathmain.py
File metadata and controls
40 lines (32 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Pair = tuple[int, int]
SumGroup = tuple[int, list[Pair]]
def equal_sum_pairs(numbers: list[int]) -> list[SumGroup]:
"""Group index-ordered pairs by their sum, keeping only shared sums."""
if not all(isinstance(x, int) for x in numbers):
raise TypeError("numbers must contain only ints")
pairs_by_sum: dict[int, list[Pair]] = {}
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
pair = (numbers[i], numbers[j])
total = numbers[i] + numbers[j]
pairs_by_sum.setdefault(total, [])
if pair not in pairs_by_sum[total]:
pairs_by_sum[total].append(pair)
result: list[SumGroup] = []
for total in sorted(pairs_by_sum):
pairs = pairs_by_sum[total]
if len(pairs) > 1:
result.append((total, sorted(pairs)))
return result
def render_output(grouped_pairs: list[SumGroup]) -> str:
"""Render grouped pairs, one line per sum, in the expected format."""
lines = []
for total, pairs in grouped_pairs:
joined = " ".join(f"( {a}, {b})" for a, b in pairs)
lines.append(f"Pairs : {joined} have sum : {total}")
return "\n".join(lines)
if __name__ == "__main__":
a = [6, 4, 12, 10, 22, 54, 32, 42, 21, 11]
print(f"First input:\n{render_output(equal_sum_pairs(a))}")
b = [4, 23, 65, 67, 24, 12, 86]
print(f"Second input:\n{render_output(equal_sum_pairs(b))}")