ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
s = 'aabbbc'
out = []
i = 0
while i < len(s):
    j = i
    while j < len(s) and s[j] == s[i]:
        j += 1
    out.append(s[i] + str(j - i))
    i = j
print(''.join(out), len(out))
  1. A. a2b3c1 6
  2. B. a2b3 2
  3. C. a2b3c1 3
  4. D. a2b3c 3

Correct answer: C. a2b3c1 3

This is run-length encoding. Each run of equal characters is written as its letter followed by its length. The runs are aa, bbb and c, so there are three runs.

More Python Programming questions

Exams that ask this topic