1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python で Project Euler #17「数字の文字数」

Posted at

Problem 16 「数字の文字数」

1 から 5 までの数字を英単語で書けば one, two, three, four, five であり, 全部で 3 + 3 + 5 + 4 + 4 = 19 の文字が使われている.
では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば, 全部で何文字になるか.
注: 空白文字やハイフンを数えないこと. 例えば, 342 (three hundred and forty-two) は 23 文字, 115 (one hundred and fifteen) は20文字と数える. なお, "and" を使用するのは英国の慣習.

Python
# n = 5
n = 1000

numbers = {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", 1000:"one thousand"}

def number_to_word(num):
  if num in numbers:
    return numbers[num]
  elif num < 100:
    a = num % 10
    b = (num // 10) * 10
    return number_to_word(b) + "-" + number_to_word(a)
  else:
    a = num % 100
    b = num // 100
    if a == 0:
      return number_to_word(b) + " hundred"
    else:
      return number_to_word(b) + " hundred and " + number_to_word(a)

def to_character_num(word):
  return len(word.replace(" ", "").replace("-", ""))

seq = range(1, n+1)
words = map(number_to_word, seq)
result = sum(map(to_character_num, words))

print result
print result == 21124
print words[:6]
print words[-3:]
結果
21124
True
['one', 'two', 'three', 'four', 'five', 'six']
['nine hundred and ninety-eight', 'nine hundred and ninety-nine', 'one thousand']
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?