I saw a tictoc during the week where a girl asked her dad:
A builder built 100 houses and wanted to put on house numbers, starting with number '1'. How number 9s will the builder need?
We are going to use python to answer the much harder question:
A builder built 1,000,000 houses and wanted to put on house numbers, starting with one. How number 9s will the builder need?
If you would like some help the following are some hints that may be of use:
(creating a loop to run over all house numbers)
We want to create a loop that runs from 1 to 1,000,000. We can use the range function for this. For example the code
for k in range(1,21):
print(k)
will print out the numbers 1, 2,3, ..., 20. Remember, range counts up to but does not include the end value.
(converting from number to string)
When checking what digits are in a number it is easier to first convert to a string and then check using characters. So we use '9' rather than 9. But how do we convert a number to a string? We use the function str.
for k in range(1,21):
print(str(k))
will print out the numbers 1, 2,3, ..., 20. Notice that it is the same output as before but now everything is a string.
(looping over characters in a string)
We want to look at each digit in the current number. Since str(k) is a string we can loop over each digit with a (second) for loop.
for digit in str(k):
print(digit)
will print out all of the digits (one per line) of the number k.
(testing if a digit is a "9")
'9' that we find so we
for loops) we create an indentifier, say total=0.for loops) we add one to total whenever we find a '9'.
The code for updating total is similar to what we use when we update the score in our games.for loops) we output the value of total.