Number Letter Counts
If the numbers to are written out in words: one, two, three, four, five, then there are letters used in total.
If all the numbers from to (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, (three hundred and forty-two) contains letters and (one hundred and fifteen) contains letters. The use of "and" when writing out numbers is in compliance with British usage.
1~1000까지의 숫자를 영어로 표현했을 때 사용한 글자수를(ex. 342 = three hundred and forty-two로 공백과 -는 제외하여 23글자) 전부 구하는 문제이다.
우선 숫자를 영어 표기로 바꾸는 절차가 필요한데... 당장 생각나는 방법은 자연수 n을 받았을 때 숫자를 자릿수마다 나눠서 그 숫자에 맞는 글자를 출력해주고 전부 합치는 방식이다. 우선 자리마다 출력할 영어의 리스트를 생성해주자.
//Python
# 1의 자리 (0의 경우 빈 str)
units = [
"",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
]
# 10~19 예외처리용
teens = [
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
]
# 10의 자리 (0, 1의 경우 빈 str)
tens = [
"",
"",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
]
10~19는 별도의 규칙을 가지고 있으니 십의 자리수가 1인 경우도 예외처리를 위해 비워놨다.
백의 자리는 units
에 "hundred"만 더해주면 되니 따로 작성하지 않았다.
다음은 자연수 n을 영어표기로 바꾸어주는 함수를 작성해보자.
def to_english(n):
if 1 <= n < 10: #1~9
return units[n]
elif n < 20: #10~19
return teens[n % 10]
elif n < 100: #20~99
ten = tens[n // 10]
unit = units[n % 10]
return ten + unit
elif n < 1000: #100~999
hundred = units[n // 100] + "hundred"
ten = (n // 10) % 10
if ten == 1:
ten = teens[n % 10]
unit = ""
else:
ten = tens[ten]
unit = units[n % 10]
return hundred + "and" + ten + unit
elif n == 1000:
return "onethousand"
else:
return "out of range"
위 함수를 거치면 공백과 - 없이 필요한 글자만이 출력된다.
이제 반복문을 통해 모든 글자수를 합치면 된다.
letters = 0
for n in range(1000):
letters = letters + len(to_english(n+1))
print(letters)
>>> 21151
21151로 답을 제출했더니 오답이었다. 어느 부분이 잘못된걸까... 살펴보니 to_english(100)
같이 100으로 나누어지는 숫자에서도 끝에 "and"가 들어가게 코드를 작성하였다. n % 100 == 0
일 때 예외처리를 해주자. 그렇게 나온 최종 코드는 다음과 같다.
# 1의 자리 (0의 경우 빈 str)
units = [
"",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
]
# 10~19 예외처리용
teens = [
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
]
# 10의 자리 (0, 1의 경우 빈 str)
tens = [
"",
"",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
]
def to_english(n):
if 1 <= n < 10: #1~9
return units[n]
elif n < 20: #10~19
return teens[n % 10]
elif n < 100: #20~99
ten = tens[n // 10]
unit = units[n % 10]
return ten + unit
elif n < 1000: #100~999
if n % 100 == 0:
hundred = units[n // 100] + "hundred"
else:
hundred = units[n // 100] + "hundredand"
ten = (n // 10) % 10
if ten == 1:
ten = teens[n % 10]
unit = ""
else:
ten = tens[ten]
unit = units[n % 10]
return hundred + ten + unit
elif n == 1000:
return "onethousand"
else:
return ""
letters = 0
for n in range(1000):
letters = letters + len(to_english(n+1))
print(letters)
>>> 21124
오늘은 여기까지.
-2025.01.06-