_Sudal 2019. 3. 5. 05:00

Question: 


If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.


If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?


NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

문제:

1부터 5까지의 숫자를 영어로 쓰면 one, two, three, four, five 이고,
각 단어의 길이를 더하면 3 + 3 + 5 + 4 + 4 = 19 이므로 사용된 글자는 모두 19개입니다.


1부터 1,000까지 영어로 썼을 때는 모두 몇 개의 글자를 사용해야 할까요?


참고: 빈 칸이나 하이픈('-')은 셈에서 제외하며, 단어 사이의 and 는 셈에 넣습니다.

예를 들어 342를 영어로 쓰면 three hundred and forty-two 가 되어서 23 글자,
115 = one hundred and fifteen 의 경우에는 20 글자가 됩니다.


Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def digits(n):
    return len(list(str(n)))
 
 
def onedigit(n): 
    if n == 1 or n == 2 or n == 6# one two six
        return 3
    elif n == 3 or n == 7 or n == 8# three seven eight
        return 5
    elif n == 0# 0
        return 0
    else# four five nine
        return 4
    
def twodigit(n): # 20, 30, ... , 90
    if n == 2 or n == 3 or n == 8 or n == 9# twenty thrity eighty ninety
        return 6
    if n == 4 or n == 5 or n == 6# forty fifty sixty
        return 5
    if n == 7# seventy
        return 7
 
def tens(n): # 10 <= 19
    if n == 10# ten
        return 3 
    elif n == 11 or n == 12# eleven twelve
        return 6
    elif n == 13 or n == 14 or n == 18 or n == 19# thirteen fourteen eighteen nineteen
        return 8
    elif n == 15 or n == 16# fifteen sixteen
        return 7
    elif n == 17# seventeen
        return 9
    
def countTens(n):
    if n // 10 == 1:
        return tens(n)
    else:
        return twodigit(n // 10+ onedigit(n % 10
    
def countLetter(n):
    if digits(n) == 1:
        return onedigit(n)
    elif digits(n) == 2:
        return countTens(n)
    elif digits(n) == 3:
        if n % 100:
            return onedigit(n // 100+ 7 + 3 + countLetter(n % 100)
        else:
            return onedigit(n // 100+ 7
    elif digits(n) == 4:
        return onedigit(n // 1000+ 8
    
import time
start = time.time()
print(sum([countLetter(x) for x in range(1,1001)]))
print('Found in ...%.5fs'%(time.time()-start))
cs



자릿수에 따른 숫자의 글자 수를 출력하는 함수를 일일이 만들었다.


0.00326s 걸렸다!