问题描述
某人从1990年1月起便开始‘三天打鱼两天晒网’,问这个人在以后的某一天是‘打鱼’还是‘晒网’
问题分析
- 计算从1990年1月到指定日期共有多少天
- 打鱼和晒网周期为5天,计算出的天数用除以5
- 根据余数判读判断是打鱼还是晒网, 若余数是1,2,3 则他在打鱼,否则在晒网。
算法设计
-
首先考虑闰年,闰年二月为29天,平年二月为28天。
判断闰年方法:能被4整除并不能被100整除或者能被400整除,即是闰年。 -
算法的核心是得到指定日期距离1990年1月1日的天数
totalDay=1990年只指定年的前一年共有多少天+指定年中到指定日期的天数 -
另设置一个月份数组int perMonth[13]存放每月的天数,
-
利用年份作为循环变量,要判断指定年份之前的每一年是否为闰年,若是闰年执行totalDay=totalDay+366,否则执行totalDay=totalDay+365; 对于指定年份,也要判断是否是闰年。
根据以上,
首先设计输入日期方式
print('please input 指定日期,包括年,月,日 如:1991 1 31')
year,month,day=[int(i) for i in input().split()]
设计一个函数 countDay(currentDay)实现求总天数的功能, 设计一个函数runYear(year)来判断是否是闰年。
def runYear(year):
if (year%4==0 and year%100!=0 or (year%400==0)): #判断是闰年条件 %代表整除
return 1
else:
return 0
def countDay(currentDay): #计算指定日期距离1990年1月1日的天数
#每月天数数组
perMonth=[0,31,28,31,30,31,30,31,31,30,31,30]
totalDay=0
year=1990
while year < currentDay['year']:
if runYear(year)==1:
totalDay=totalDay+366
else:
totalDay=totalDay+365
year+=1
#如果是闰年,则二月是29天
if runYear(currentDay['year']==1):
perMonth[2]+=1
i=0
while i < currentDay['month']: #将本年内的天数累加到totalDay中
totalDay+=perMonth[i]
i+=1
totalDay+=currentDay['day']
return totalDay
Code
# !/user/bin/python3
# -*- coding: utf-8 -*-
# @author: HHVic
# @desc: 三天打鱼两天晒网
import time
# add timer to calculate the performance
# Basic performance
###############################################################
start = time.time()
def runYear(year):
if (year%4==0 and year%100!=0 or (year%400==0)): #判断是闰年条件 %代表整除
return 1
else:
return 0
def countDay(currentDay): #计算指定日期距离1990年1月1日的天数
#每月天数数组
perMonth=[0,31,28,31,30,31,30,31,31,30,31,30]
totalDay=0
year=1990
while year < currentDay['year']:
if runYear(year)==1:
totalDay=totalDay+366
else:
totalDay=totalDay+365
year+=1
#如果是闰年,则二月是29天
if runYear(currentDay['year']==1):
perMonth[2]+=1
i=0
while i < currentDay['month']: #将本年内的天数累加到totalDay中
totalDay+=perMonth[i]
i+=1
totalDay+=currentDay['day']
return totalDay
if __name__=='__main__':
while True:
print('please input 指定日期,包括年,月,日 如:1991 1 31')
year,month,day=[int(i) for i in input().split()]
#定义一个日期字典
today={'year':year,'month':month,'day':day}
totalDay=countDay(today) #求出指定日期距离1990年1月1日的天数
print('%d年%d月%d日与1991年1月1日相差%d天' %(year,month,day,totalDay))
#天数%5,判断输入打鱼还是晒网
result=totalDay%5
if result>0 and result<4:
print('今天打鱼')
else:
print('今天晒网')
end = time.time()
print("The Basic Runtime is {0}".format((end-start)))
结果
please input 指定日期,包括年,月,日 如:1991 1 31
2021 8 1
2021年8月1日与1991年1月1日相差11537天
今天打鱼