“三天打鱼,两天晒网”
题目:
中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。
基本要求:1.程序风格良好(使用自定义注释模板),提供友好的输入输出。
提高要求:1.输入数据的正确性验证。
2.使用文件进行数据测试。如将日期 20100101 20111214 等数据保存在in.txt文件中,程序读入in.dat文件进行判定,并将结果输出至out.txt文件。
题目分析:
三天打鱼,两天晒网。周期为5天。主要计算所要查询日期相距2010年1月1日共有多少天,则分别计算出所查询年份前几年距2010年1月1日的天数,再分别计算当年查询当月前几月的天数和当月的天数,然后都加起来得到总天数。最终用总天数除5求余数,若为1,2,3的话这个人当天在打鱼,若为0,4的话这个人当天在晒网。
重点:
1.要考虑闰年和平年(闰年为可以被4整除并且不能被100整除或者能被400整除,2月有29天,一年有366天;平年二月28天,一年365天。)
2.各个月天数不一样
程序流程图:
关键代码(Python):
1.定义函数result()用来计算总天数及判断此人当天在晒网还是打鱼。
(1)将date_input转换为列表并赋给date,然后分别获取年月日。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210326172418488.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhX19fX19faGFoYQ==,size_16,color_FFFFFF,t_70)
(2)计算所查询年份不包括当月的前几月份的天数。
(3)计算之间有几个闰年。
(4)计算总共的天数all_days,并求出余数。
(5)输出判断结果到out.txt中。
2.从文件in.txt中获取所要查询的日期。
(1)利用方法readlines()把in.txt中的每行文本作为一个字符串存入列表中,并返回该列表给变量date_fp1。
(2)先用方法len()计算列表data_fp1的长度,再使用for循环分别将每行日期赋给变量date_input,然后调用函数result()获取相应的结果。
测试程序
In.txt中逐行输入日期,其中最后两组数据是不正确的。
测试结果
总结:
本次代码的编写过程中,首先应该先通过分析题目得出题目解法的核心思路,然后再去解决问题。在这次作业中我学到了很多Python的知识,如文件的使用、简单的选择结构、循环结构等。
不足之处:未实现使用in.dat文件进行判定,还有最终实现结果没那么简要,有很多多余的输出。还是要掌握更多基础知识。
代码:
‘’’ 三天打鱼,两天晒网
自2010年01月01号开始
问这个人在之后的某一天中在大鱼还是晒网 ‘’’
周期为5天,1,2,3天在打鱼,4,5天在晒网
总天数除以5,看余数,若为1,2,3在打鱼,4,0在晒网
def result(date_input):
date = list(date_input)
fp = open(‘D:/pythonProject/out.txt’, ‘a+’)
# 分别表示当前所查询年、月、日
date_year = int(date[0]+date[1]+date[2]+date[3])
date_month = int(date[4]+date[5])
date_day = int(date[6]+date[7])
if date_day in range(32, 100):
print(‘您输入的日期中当月天数有误!!!’, file=fp)
# 计算所查询年份中的天数
m_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = 0
n = 0
if date_month in range(13,100):
print('您输入的日期中月份有误!!!', file=fp)
else:
for i in range(0, date_month - 1):
days += m_days[i]
# 判断两年份之间有多少个闰年,用leap_year表示
leap_year = 0
for i in range(2010, date_year):
if (i % 4 == 0 and i % 400 != 0) or (i % 400 == 0):
leap_year += 1
# 计算两日期之间共有多少天,用all_days表示
all_days = days + date_day + leap_year + (date_year - 2010) * 365
if ((date_year % 4 == 0 and date_year % 400 != 0) or (date_year % 400 == 0)) and (date_month > 2):
all_days += 1
# 算总天数除5的余数
num = all_days % 5
# 输出查询信息
# 判断这天是在打鱼还是晒网,并进行要求的文件操作
print('您输入的日期为%d年%d月%d日,距2010年1月1日有%d天'% (date_year, date_month, date_day, all_days), file=fp)
if all_days <= 0:
print('您输入的日期有误!!!\n', file=fp)
elif num in [1, 2, 3]:
print('当天这个人在打鱼!\n', file=fp)
elif num in [0, 4]:
print('这个人当天在晒网!\n', file=fp)
with open(‘D:/pythonProject/in.txt’, ‘r’) as fp1:
date_fp1 = fp1.readlines()
for i in range(0, len(date_fp1)):
date_input = date_fp1[i]
result(date_input)
fp1.close()