I'm trying to become more proficient in Python and have decided to run through the Project Euler problems.
In any case, the problem that I'm on (17) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.
I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.
FYI on the code: I have a function (
num2eng) which translates the given integer into English words but does not include the word "and".
for i in range (1, COUNTTO + 1): container = num2eng(i) container = container.replace(' ', '') print container if i > 100: if not i % 100 == 0: length = length + container.__len__() + 3 # account for 'and' in numbers over 100 else: length = length + container.__len__() else: length = length + container.__len__() print length
So there is some repetition in my code and some nesting, both of which seem un-pythonic. Any suggestions on ways to simplify it are very much appreciated!
Edit: I'm specifically looking for ways to make the script shorter and with simpler loops, I think that's my biggest weakness in general. The answers below are perfect, thanks everyone!
Edit #2: Changed the title.