三天打鱼两天晒网问题Python求解
目录
使用Python求解三天打鱼两天晒网问题。
使用Java模拟XN*2图灵机
问题:
中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。
要求
基本要求:
1.程序风格良好,提供友好的输入输出。
提高要求:
1.输入数据的正确性验证。
2.使用文件进行数据测试。如将日期 20100101 20111214 等数据保存在in.txt文件中,程序读入in.dat文件进行判定,并将结果输出至out.txt文件。
作业思路:
根据题意可以将解题过程分为三步:
1)计算从2010年1月1日开始至指定日期共有多少天;
2)由于“打鱼”和“晒网”的周期为5天,所以将计算出的天数用5去除;
3)根据余数判断他是在“打鱼”还是在“晒网”;
功能实现
1.准备
导入calendar模块,便于计算日历相关数据
calendar.leapdays(y1,y2)
# 返回在Y1,Y2两年之间的闰年总数。
calendar.isleap(year)
# 返回True或False,判断是否为闰年。
其他详细说明点击python日历模块calendar
创建输入文件,保存在in.dat中,数据如下。
2.预先处理好相关数据
monthDayCommonYear = tuple([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]) # the day of each common month
monthDayLeapYear = tuple([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]) # the day of each leap month
commonYearDays = 0
leapYearDays = 0
while iFlag < 12:
commonYearDays += monthDayCommonYear[iFlag] # the day of common year
leapYearDays += monthDayLeapYear[iFlag] # the day of leap year
iFlag += 1
3.读入dat文件
f = open(r"C:\Users\moree\Desktop\in.dat", 'r') # the absolute file path
lines = f.readlines()
f.close()
4.判断输入数据是否合法:
分为年,月,日的判断
年份>2010,0<日期<(大月32||小月31),0<月份<13,0<二月<(闰年30||平年29);
if nyear < 2010 or nmonth > 12 or nmonth < 1 or nday < 1:
print("illegal input!"