코딩라이브러리/파이썬

파이썬 윤년 계산하기 (with 백준 2753)

유니네 라이브러리 2024. 6. 7. 15:59

파이썬 윤년 계산은 calendar 모듈의 isleap() 함수 사용한다.

  • calendar.isleap(year)
    year 윤년이면 True, 아니면 False 반환
import calendar as cd
y = int(input()) #년도 입력 yyyy

if (cd.isleap(y)): #윤년이면 True 반환
    print(f"입력한 연도는 윤년입니다.: {cd.isleap(y)}")
else: #윤년이 아니면 False 반환
    print(f"입력한 연도는 윤년이 아닙니다.: {cd.isleap(y)}")

 

isleap() 함수를 사용하지 않고 직접 계산하여 윤년 계산할 수 있다.

이는 백준 2753 문제 풀이로 연습.

 

▶ 윤년 연습 백준 문제 풀이

https://www.acmicpc.net/problem/2753

백준 2753 - 윤년계산

"""
입력
첫째 줄에 연도가 주어진다. 연도는 1보다 크거나 같고, 4000보다 작거나 같은 자연수이다.

출력
첫째 줄에 윤년이면 1, 아니면 0을 출력한다.
"""
yyyy = int(input())

if (yyyy % 4 == 0 and (yyyy%100 != 0 or yyyy%400 == 0)): # 윤년
    print("1")
else:
    print("0")
"""
입력
2000
출력
1
입력
1999
출력
0
"""

 

☞ 파이썬 자습서 참고 사이트

 

calendar — General calendar-related functions

Source code: Lib/calendar.py This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have...

docs.python.org