Special Occurrence
Source: Dec 2023, Task 3 (DTU 02002/02003). Study solution — not an official answer key.
Problem
A special occurrence is a 5 followed by two numbers where exactly one is 7.
Write special_occurrence(sequence) returning the index of that 5, or -1 if none.
Example
>>> special_occurrence([2, 8, 11, 3, 12, 5, 7, 7, 11, 3, 12, 5, 2, 7, 5, 7, 2, 6])
11
Approach
Scan triples (sequence[i], sequence[i+1], sequence[i+2]). When the first is 5, check that exactly one of the next two equals 7.
Solution
Show solution Hide solution
Solution
def special_occurrence(sequence):
for i in range(len(sequence) - 2):
if sequence[i] == 5:
a = sequence[i + 1]
b = sequence[i + 2]
if (a == 7) + (b == 7) == 1:
return i
return -1