파이썬_실전 프로젝트

프로젝트 오일러 19번 - 일요일의 갯수

1901년 1월 1일부터 2000년 12월 31까지 매달 1일이 일요일인 날수를 계산하는 문제입니다.

 

Counting Sundays

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)?

 

년,월,일 루프문을 세개 중첩하고, 월,일 루프문 사이에 윤달 조건문을 추가해 주고,

최종 count 할때는, 날짜가 1일이고 요일이 일요인지를 판단해서 카운트를 해주면 됩니다.

요일은, 1900년 1월1일을 월요일을 의미하는 '0'으로 주고, 날짜를 총합해서, 7로 나누면 6이 나올때마다 일요일입니다.

 

루프문 만들기

매월 날짜수를 리스트에 저장해놓고, 년월일을 의미하는 루프문 세개를 만들었습니다.

daylist = [31,28,31,30,31,30,31,31,30,31,30,31]
total=0

for y in range(1900,2001):
    for m in range(12):
        for d in range(daylist[m]):
            total+=1

print(total)
36865

 문제는 1901년부터 계산하는거지만, 1900년 1월1일이 월요일에서부터 요일을 계산해야 되서, 1900년부터 루프문을 만들었습니다.

 

윤달 조건문 넣기
daylist = [31,28,31,30,31,30,31,31,30,31,30,31]
total=0

for y in range(1900,2001):
    for m in range(12):
        day=daylist[m]
        if y%4==0 and m==1: 
            day+=1
        for d in range(day):
            total+=1

print(total)
36891

 4년마다 윤달때문에 하루가 길어지기 때문에, 날짜 루프문 앞에 조건문을 걸어서, 4년마다 2월달(m=1)에 하루를 추가했습니다.

 

 요일계산
daylist = [31,28,31,30,31,30,31,31,30,31,30,31]
total=0

for y in range(1900,2001):
    for m in range(12):
        day=daylist[m]
        if y%4==0 and m==1: 
            day+=1
        for d in range(day):
            if total%7==6:
                print(y,m+1,d+1)
            total+=1

print(total)
1900 1 7
1900 1 14
1900 1 21
1900 1 28
1900 2 4
1900 2 11
1900 2 18
1900 2 25
1900 3 3
1900 3 10

 7로 나누어서 6인날, 일요일인 날만 출력한 결과입니다. 제대로 나온건지 실제 달력이랑 한번 비교해보세요.

 

카운트 하기

요일까지 확인했으면, 이제 카운트를 하면 됩니다.

daylist = [31,28,31,30,31,30,31,31,30,31,30,31]
total=0
count=0

for y in range(1900,2001):
    for m in range(12):
        day=daylist[m]
        if y%4==0 and m==1: 
            day+=1
        for d in range(day):
            if y>1900 and d==0 and total%7==6:
                count+=1
            total+=1

print(total,count)
36891 171

 요일을 비교하는 조건문에 매월1일을 의미하는 d==1 을 넣어주고, 루프문을 1900년부터 시작했기 때문에, 년도도 1901년으로 걸러주면 됩니다.

 

댓글

댓글 본문
  1. 이제동
    그냥 100년동안 매월 1일은 총 1200번 있으니까 1200/7 하니까 171.4 나오네요.
    코딩으로 풀다가 이렇게 맞추면 뭔가 재밌더군요.
  2. nomadlife
    아,, 오타군요 ^^ 감사합니다. year % 100 != 0 입니다. 띄어쓰기를 안하고 쓰니깐,, year0 != 0 이렇게 되네요. 뭔가 공격코드 같은걸로 인식하는듯 합니다.
    대화보기
    • 나바자
      if month[0]=='Feb' and year%4==0 and year0!=0:
      NameError: name 'year0' is not defined

      으로 에러가 나네요.. ㅠㅠ
    버전 관리
    nomadlife
    현재 버전
    선택 버전
    graphittie 자세히 보기