Skip to content

Instantly share code, notes, and snippets.

@sempr
Last active July 5, 2018 03:19
Show Gist options
  • Save sempr/d718cd22f5ce42e5c2236814915e845b to your computer and use it in GitHub Desktop.
Save sempr/d718cd22f5ce42e5c2236814915e845b to your computer and use it in GitHub Desktop.
0705.py
#coding:utf8
import sys
## prepare
d_arr = (
(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
)
ds_arr = (
(None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365),
(None, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366),
)
## prepare end
## cache is leap year
def is_leap_year_old(y):
"""闰年判断 这样最快"""
return (y % 4 == 0) and (y % 100 != 0 or y % 400 == 0)
def leap_count_old(year):
"""从0年开始的闰年数量(不包含0年)"""
return year // 4 - year // 100 + year // 400
is_leap_array = [is_leap_year_old(y) for y in range(10000)]
### leap_count_array[i]是i年1月1日的day_id 所以要计算截止前一年的闰年数量
leap_count_array = [leap_count_old(y-1)+365*y for y in range(10000)]
## cache is leap year end
def solve(y, m, d, n):
ny, nm = y + n // 12, m + n % 12
if nm > 12:
ny += 1
nm -= 12
is_leap_ny = is_leap_array[ny]
is_leap_y = is_leap_array[y]
nd = d_arr[is_leap_ny][nm]
if d < nd:
nd = d
return leap_count_array[ny] + nd + ds_arr[is_leap_ny][nm] \
- (leap_count_array[y] + d + ds_arr[is_leap_y][m])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment