Reading a problem
A problem has three parts, and each one earns its keep:
- The statement says what to compute. Underline every rule: "strictly", "at different positions", "empty gives 0".
- The examples show the rules at work. Check your reading against them before you code.
- The constraints (sizes, ranges, "at least 1 element") tell you what inputs can occur, and how fast the code must be.
Turn each example into a call of your own, and compare it with the expected answer:
print(solution(" hello world ")) # the statement says 2
Do this before you submit. A wrong example is a misread statement, and it is the cheapest bug to fix.
See it run
def solution(text): return len(text.split()) example = " hello world " print(solution(example) == 2)
An example from the statement becomes a call you can check yourself.
Practice reading a problem
Exercise 1
Write solution(text) that returns how many words text has. Words are separated by one or more spaces, and text may start or end with spaces. Text with no words gives 0. For example, solution("the quick fox") is 3 and solution(" hello world ") is 2.
Exercise 2
A row of buildings has the heights in heights, all zero or more. A building is visible from the left if it is strictly taller than every building before it. The first building is always visible. Write solution(heights) to return how many are visible. For example, solution([3, 1, 4, 4, 5]) is 3 (the 3, the first 4 and the 5), and solution([5, 4, 3]) is 1. There is at least one building.
Exercise 3
A locker code is valid when it has exactly 5 characters: the first 2 are letters (upper or lower case) and the last 3 are digits. Write solution(code) returning True for a valid code and False otherwise. For example, "ab123" is valid, "a1234" and "abc12" are not.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.