Skip to content
CodeItRaw
Strings

Lesson 2/3

Most text questions are solved by walking the characters once while carrying a small state: "am I inside a word right now?", "how long is the current run?". At every character the state is updated and, where needed, a counter goes up.

digits = 0
inside = False
for ch in text:
if ch.isdigit():
if not inside:
digits += 1
inside = True
else:
inside = False
return digits
Counting the numbers in a text ("a12b7" holds two): the counter goes up only at the moment a number is entered, that is, when a digit is seen and the character before was not one. inside remembers what the previous character was.

The longest run of the same character is the same skeleton: if the character equals the one before, lengthen the run; if not, start again at 1; update the longest at every step. It is the "compare neighbours" lesson of Arrays, in text.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Count Words

    Function

  2. 02

    Longest Run

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list