Counting Digits
January 7, 2020
We have a simple homework question today:
Given a range of non-negative integers, count the number of 2s, 5s and 8s in the decimal representations of the digits. For instance, from 295 to 305, there are 9:
295: 2 296: 1 297: 1 298: 2 299: 1 300: 0 301: 0 302: 1 303: 0 304: 0 305: 1 Total 9
Your task is to write a program to count the 2, 5, and 8 digits in the range of integers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Happy new year & I hope everyone enjoyed the holiday break.
I thought that should be a more direct way of counting the digits than enumerating the entire range. For simplicity, dcount counts all the digits in range(n) – ie. not including n itself:
That needs some modification for digit ‘0’ (an exercise for the reader)- also the while condition can be ‘n > m’
This is better (and the ‘0’ count is correct if we assume numbers are zero padded on the left to the same length):
Or wrap the whole thing up in a list comprehension:
Klong version
Klong results:
{+/{[n];n::x;+/{#($n)?$x}'”258″}’x+!1+y-x}(295;305)
9
Here’s a solution in Python, based on the digit counting algorithm from here.
Output: