S2Q2 · Find Sum and Absolute Difference Alternately¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: for odd-numbered pairs (1, 3, 5…) print the sum; for even-numbered pairs (2, 4, 6…) print the absolute difference.
n = int(input())
for i in range(1, n + 1):
a, b = map(int, input().split(","))
if i % 2 == 1:
print(a + b)
else:
print(abs(a - b))
Key rules: - Pairs are 1-indexed: pair 1, 2, 3, … - Odd pair number → sum - Even pair number → absolute difference - Input is comma-separated (no spaces)
Problem Statement¶
Problem (I/O type)
Read n comma-separated pairs. Print the sum for odd-numbered pairs and the absolute difference for even-numbered pairs.
Example:
3
1,2
3,5
4,3
3
2
7
Tracing the example¶
| Pair # | Input | Odd or even? | Operation | Output |
|---|---|---|---|---|
| 1 | 1,2 |
Odd | 1+2 |
3 |
| 2 | 3,5 |
Even | \|3-5\| |
2 |
| 3 | 4,3 |
Odd | 4+3 |
7 |
Solution approaches¶
n = int(input())
pairs = [input().split(",") for _ in range(n)]
for i, (a_str, b_str) in enumerate(pairs, 1):
a, b = int(a_str), int(b_str)
print(a + b if i % 2 == 1 else abs(a - b))
enumerate(pairs, 1) gives 1-based pair numbers automatically.
n = int(input())
pairs = [list(map(int, input().split(","))) for _ in range(n)]
results = list(map(
lambda pair: pair[0][0] + pair[0][1] if pair[1] % 2 == 1 else abs(pair[0][0] - pair[0][1]),
zip(pairs, range(1, n + 1))
))
print("\n".join(map(str, results)))
zip(pairs, range(1, n+1)) pairs each input pair with its 1-based index. The lambda decides sum or abs diff. "\n".join(...) prints all results at once.
Key takeaways¶
1-indexed with range(1, n+1)
Using range(1, n+1) gives loop variable i starting at 1. Then i % 2 == 1 is True for odd pairs - no off-by-one adjustment needed.
input().split(",") for comma-separated input
When the separator is a comma (not whitespace), use split(",") explicitly. The default split() splits on any whitespace and would fail here.
abs() for absolute difference
abs(a - b) handles both a > b and b > a in one expression. Never write if a > b: a-b else: b-a when abs() does it cleanly.