Predict the output
What does this print?
text = "aaa"
count = 0
for centre in range(2 * len(text) - 1):
lo, hi = centre // 2, centre // 2 + centre % 2
while 0 <= lo and hi < len(text) and text[lo] == text[hi]:
count += 1
lo, hi = lo - 1, hi + 1
print(count)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 6
Right: three single letters, two 'aa' and one 'aaa'.
Counting by position means repeats such as the two 'aa' stretches both count, which the centre walk handles naturally.
Why not the others?
- B 3. The gaps between letters are centres too.
- C 4. Each 'aa' is counted at its own position.