본문 바로가기

파이썬

[Project Euler]17. Number letter counts

[문제]
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

 

[풀이]
dic={0:0,1:3,2:3,3:5,4:4,5:4,6:3,7:5,8:5,9:4,10:3,
     11:6,12:6,13:8,14:8,15:7,16:7,17:9,18:8,19:8,20:6,
     30:6,40:5,50:5,60:5,70:7,80:6,90:6,100:7,1000:11}

result = 0

for i in range(1,1001):
    if len(str(i))==1:
        result+=dic.get(i)

    elif len(str(i))==2:
        if dic.get(i,0)==0:
            result+=dic.get(int(str(i)[0])*10)+dic.get(int(str(i)[-1]))
        else:
            result+=dic.get(i)

    elif len(str(i))==3:
        if i%100==0:
            digits3=dic.get(int(str(i)[0]))+dic.get(100)
        else:
            digits3=dic.get(int(str(i)[0]))+dic.get(100)+3

        if dic.get(int(str(i)[1:]),0)==0:
            result+=dic.get(int(str(i)[1])*10)+dic.get(int(str(i)[-1]))+digits3
        else:
            result+=dic.get(int(str(i)[1:]))+digits3

    else:
        result+=dic.get(i)

print(result)

 

'''
우선,, 영어로 숫자 세는 방법부터 찾아봤다...
1부터 20까지는 규칙이 없어 일단 다 dict에 넣어줬고
그 뒤로 30,40,50,60,70,80,90,100,1000을 넣어줬다
(서로 조합해서 모든 숫자를 만들 수 있는 최소 구성만!)

그리고 한자리, 두자리, 세자리, 네자리로 나눠서
조합해서 구했다!

중간에 digits3는 one hundred처럼 백의 자리일 때 숫자 개수를 구한 것이다.
백의 자리를 구한 다음 두자리를 구해서 백의 자리를 더했다.
100으로 나눠지는 수(100,200,300,400...)는 and가 포함되지 않는다.

그래서 100으로 나눠지지 않는 수는 +3(and)를 해주었다.
'''

'파이썬' 카테고리의 다른 글

[Project Euler]19. Counting Sundays  (0) 2021.07.04
[Project Euler]18. 못풀었음  (0) 2021.06.29
[Project Euler]16. Power digit sum  (0) 2021.06.10
[Project Euler]15. Lattice paths  (0) 2021.06.09
[Project Euler]14. Longest Collatz sequence  (0) 2021.06.09