S2Q1 · Check for Arithmetic Progression¶
⚡ Quick Reference
Function: is_arithmetic_progression(sequence: list) -> bool
Core idea: compute the common difference from the first two elements, then verify all consecutive pairs have the same difference.
def is_arithmetic_progression(sequence: list) -> bool:
if len(sequence) <= 1:
return True
diff = sequence[1] - sequence[0]
return all(sequence[i] - sequence[i-1] == diff
for i in range(2, len(sequence)))
Key rules:
- Sequences of length 0 or 1 are trivially AP
- Compute diff = sequence[1] - sequence[0]
- All consecutive differences must equal diff
Problem Statement¶
Problem
Write a function is_arithmetic_progression(sequence) that returns True if consecutive differences are all equal.
Examples:
[1, 3, 5, 7, 9]
True
[9, 6, 3, 0, -3, -6]
True
[1, 3, 5, 6, 11]
False
Tracing all examples¶
| Sequence | diff |
All equal? | Result |
|---|---|---|---|
[1,3,5,7,9] |
2 | 2,2,2,2 ✅ | True |
[2,4,6,8,10] |
2 | 2,2,2,2 ✅ | True |
[9,6,3,0,-3,-6] |
-3 | -3,-3,-3,-3,-3 ✅ | True |
[1,3,5,6,11] |
2 | 2,2,1,5 ❌ | False |
[0,0,0,0,0] |
0 | 0,0,0,0 ✅ | True |
[1,2,4,8,16] |
1 | 1,2,4,8 ❌ | False |
Solution approaches¶
def is_arithmetic_progression(sequence: list) -> bool:
if len(sequence) <= 1:
return True
diffs = [b - a for a, b in zip(sequence, sequence[1:])]
return len(set(diffs)) == 1
zip(sequence, sequence[1:]) generates all adjacent pairs. Computing their differences and checking if they all reduce to a single value confirms an AP.
Key takeaways¶
Compute diff from first pair, check all others
diff = sequence[1] - sequence[0] establishes the expected common difference. Then verify every subsequent pair matches. This is O(n) - one pass through the sequence.
set(diffs) == 1 element - elegant check
If all differences are the same, the set of differences has exactly one element. len(set(diffs)) == 1 is a clean alternative that doesn't need to extract the first difference separately.
Handle length 0 and 1 as edge cases
A sequence with 0 or 1 element has no pairs to compare - it's trivially an AP. Without this guard, sequence[1] - sequence[0] would raise an IndexError on short sequences.