Project Euler 17 Problem Statement
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
This version improves the writing of numbers by using the correct compound form. It also extends to quadrillions with the ability to add more decades. Instead of reporting a character count the full number is spelled out. Having a program that reliably translates numbers to words is much more valuable; such as spelling out monetary amounts on checks.
Looking at the process
The grouping of the number into three digit groups is accomplished by the following line:
number = map(''.join, zip(*[iter(str(n).zfill(len(thousands)*3))]*3))
The number is always represented with leading zeros. For example, with the maximum
thousands of ‘Quadrillion’ or 1015, the number 34,509 will become 000 000 000 000 034 509 (spaces added for readability).
Next, a Python idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n), is applied to the zero-filled number. The final list named
number is compiled by the
map/join functions as:
['000', '000', '000', '000', '034', '509'] . The ‘000’ groups are ignored during processing.
Making the formatted number conform to other styles
As mentioned, this version uses the correct syntax for compound numbers such as using forty-four for 44.
Likewise, a single ‘and’ could also be included after the thousands/hundreds group when the last group is less than 100.
The program is able to be expanded to include other thousand groups by adding the group name onto the
thousands list if 999 quadrillion is not enough. I have no idea why, except for a projected U.S. deficit :).
Python 2.7 Source
Other thousands groups: Quintillion 1018, Sextillion 1021, Septillion 1024, Octillion 1027, and even more here.