[Python] 19 – Counting Sundays

문제 이해를 잘못해서 시간이 엄청 걸렸습니다.

제출을 하면 어디가 잘못되었는지가 나오지 않기 때문에 문제를 정확하게 파악해야 됩니다.

이번에 실수는 1901~2000까지 일요일의 수를 카운팅 하는건줄 알았는데 알고보니 월의 처음 시작일이 일요일인 것만 찾는 문제였습니다.

소스코드에 불필요한 부분이 많이 있더라도 파이썬에 익숙해보고자 하는 일이기 때문에 … 이해 부탁드립니다.

[문제 링크]
http://projecteuler.net/problem=19

[문제 원본]
You are given the following information, but you may prefer to do some research for yourself.

1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

[풀이 방법]
1. 1900~1901년까지 월의 시작요일이 일요일인 개수를 구한다.
2. 1900~2000년까지 월의 시작요일이 일요일인 개수를 구한다.
3. 2의 결과에서 1의 결과를 제거한다.

위와 같이 한 이유는 문제에서 주어진 처음 시작 요일이 1900년 1월 1일 이기 때문입니다.
[소스 코드]

#
#19_Counting_Sundays.py
#
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"]

'''
#### 함수 정의 부분 ####
'''
def countingSundays(sYear, eYear):
    """ 주어진 기간 동안에 월의 시작요일이 일요일인 항목은 구한다.
    :param sYear: 시작 월
    :param eYear: 마지막 월
    :return:       월의 시작 요일이 일요일인 개수
    """

    count = 0
    sumOfDays = 0

    while(sYear <= eYear) :
        if((sYear % 4 == 0 and sYear%100 != 0) or (sYear % 400 == 0)) :
            months[1] = 29
        else :
            months[1] = 28
        for i in months :
            if(days[sumOfDays % 7] == 'SUN'):
                count = count+1
            sumOfDays = sumOfDays + i
        sYear = sYear + 1

    return count

'''
#### 메인 실행 부분 ####
'''
sumUtil1901 = countingSundays(1900, 1900)
print("Sundays fell on the first of the month until 1901 =", sumUtil1901)
print("Sundays fell on the first of the month = ", countingSundays(1900, 2000) - sumUtil1901)

답글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Twitter 사진

Twitter의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

%s에 연결하는 중