Breaking a job into small jobs
Split a big task into helper functions that each answer one question. About 10 minutes.
Ask one small question
How would you count the prime numbers up to 20? You'd go through the numbers one at a time, and for each one ask: is this a prime? If yes, count it.
That's two jobs: walking through the numbers, and answering the question about one number. Keep them apart. Write the question as its own function, which returns true or false. A function that answers a yes-or-no question gets a name that sounds like a question, such as is_prime.
The helper, and the loop that uses it
A prime is a number bigger than 1 with no divisors except 1 and itself. To check, try every number from 2 up to just below it. If any of them divides it evenly, it is not a prime, so return false at once. If none do, return true.
Now the counting loop becomes easy to read: for each number, if it is prime, add one. You can test the helper alone, and then trust it inside the loop.
def is_prime(k):
if k < 2:
return False
for d in range(2, k):
if k % d == 0:
return False
return True- k
- 2
- count
- 1
Ask the helper about 2. Nothing between 2 and 2 can divide it, so it is a prime. The count is 1.
How many prime numbers are there from 1 up to 10?
- A4
- B5
- C3
Show the answer
4. They are 2, 3, 5 and 7.
Count the primes
Return how many prime numbers there are from 1 up to n. A prime is a number bigger than 1 whose only divisors are 1 and itself. Write a helper function that checks one number.
n = 10 → 4
0 ≤ n ≤ 5,000