Prob 0017 ‐ Number Letter Counts - maccergit/Euler GitHub Wiki
No special optimization tricks here - this is more of an exercise in string and number manipulation, along with software design and software engineering to help come up with a correct implementation.
01
The current skeleton is set up for Test Driven Development. Note that we can't use the core "len()" approach to counting characters, as we need to skip over spaces and hyphens in the length of the text version of the numbers. We also need to be sure we have the correct text to start with, so we have test cases for both the text and the count of the letters in the text. Finally, we have test cases for the sum of the counts - but if we have the other code working correctly, this should fall into place.
A quick lookup of the number -> string values is implemented in a dictionary. Note we only need the special cases : single digits + teens + decades, as those are the ones with special names. All others are composed from the dictionary values with spaces and/or hyphens. We don't go beyond 1000, as it's debatable what the proper text form should be ("one thousand and one hundred and eleven", "one thousand one hundred and eleven", "one thousand, one hundred and eleven"). I personally do NOT follow the "accepted British convention" and thus do not use the "and" : "one hundred forty-two" - but you need to do this to get the desired answer.
Computing the length while skipping spaces and hyphens proves to be easy by using a list comprehension to filter the spaces and hyphens from the final string, and then using "len()" to get the length. The final result scales linearly (as expected) :