一年中的第几天与一周中的第几天
作者:互联网
python
def dayOfYear(self, date: str) -> int:
year, month, day = [int(i) for i in date.split("-")]
arr = [31,28,31,30,31,30,31,31,30,31,30,31]
if year % 400 == 0 or year % 4 == 0 and year % 100 != 0:
arr[1] += 1
return day + sum(arr[:month-1])
一周中的第几天 只需在这道题的基础上稍作修改即可
因为题目给出的年份是从1971到2100,而我们通过查阅知道1970.12.31是星期四
所以通过判断距1970.12.31的天数就能知道题目给出的那天是星期几
在 一年中的第几天 的基础上加上之前年份的天数就可以了
python
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"]
days = 0
# 加上年份贡献的天数
days += 365*(year-1971) + (year-1969)//4
arr = [31,28,31,30,31,30,31,31,30,31,30,31]
if year % 400 == 0 or year % 4 == 0 and year % 100 != 0:
arr[1] += 1
days += day + sum(arr[:month-1])
return week[(days+3)%7]
或者直接用python库中的函数帮我们求解
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"]
return week[date.weekday(date(year,month,day))]
标签:arr,第几天,int,31,30,一年,year,一周 来源: https://blog.csdn.net/lucky__peng/article/details/122285892