Created
February 14, 2018 03:57
-
-
Save junichiro/e576bb09cc5c4019704981b8c7a69845 to your computer and use it in GitHub Desktop.
会社で少し盛り上がった Project Euler をやってみる 017 ref: https://qiita.com/junichiro/items/ee3a312fca2510d82d94
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
class Problem17: | |
COUNT = { | |
0: '', | |
1: 'one', | |
2: 'two', | |
3: 'three', | |
4: 'four', | |
5: 'five', | |
6: 'six', | |
7: 'seven', | |
8: 'eight', | |
9: 'nine', | |
10: 'ten', | |
11: 'eleven', | |
12: 'twelve', | |
13: 'thirteen', | |
14: 'fourteen', | |
15: 'fifteen', | |
16: 'sixteen', | |
17: 'seventeen', | |
18: 'eighteen', | |
19: 'nineteen', | |
20: 'twenty', | |
30: 'thirty', | |
40: 'forty', | |
50: 'fifty', | |
60: 'sixty', | |
70: 'seventy', | |
80: 'eighty', | |
90: 'ninety', | |
100: 'hundred', | |
1000: 'onethousand' | |
} | |
def count(self): | |
# count from 1 to 9 | |
count001_009 = sum(len(self.COUNT[i]) for i in range(1, 10)) | |
# count from 10 to 19 | |
count010_019 = sum(len(self.COUNT[i]) for i in range(10, 20)) | |
# count from 20 to 99 | |
count020_099 = sum(len(self.COUNT[i * 10]) * 10 + count001_009 for i in range(2, 10)) | |
# count from 1 to 99 | |
count001_099 = count001_009 + count010_019 +count020_099 | |
# count from 100 to 999 | |
count100_999 = sum(len(self.COUNT[i] + self.COUNT[100] + 'and') * 100 + count001_099 for i in range(1, 10)) | |
# 100, 200, ... 900 のときの and まで数えてしまっているので除外 | |
count100_999 = count100_999 - len('and') * 9 | |
# count from 1 to 999 | |
count001_999 = count001_099 + count100_999 | |
# count from 1 to 1000 | |
return count001_999 + len(self.COUNT[1000]) | |
if __name__ == '__main__': | |
p = Problem17() | |
print(p.count()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment