写一个函数[day] = weekday(M, D, Y)
,它告诉你日期M / D / Y的星期几。告诉您的用户接受的日期范围是什么。请勿使用任何特定于日历的模块或功能。
我找到了这两段代码,但我不理解它们背后的逻辑。更具体地说,我不明白偏移数字的来源。
def weekday(M,D,Y):
offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
week = ['Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday']
afterFeb = 1
if M > 2: afterFeb = 0
aux = Y - 1700 - afterFeb
# dayOfWeek for 1700/1/1 = 5, Friday
dayOfWeek = 5
# partial sum of days betweem current date and 1700/1/1
dayOfWeek += (aux + afterFeb) * 365
# leap year correction
dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400
# sum monthly and day offsets
dayOfWeek += offset[M - 1] + (D - 1)
dayOfWeek %= 7
return dayOfWeek, week[dayOfWeek]
def weekday(m, d, y):
# following numbers in the array are suggested by Sakamoto, Lachman,
Keith and Craver
# one for each month
# and the remaining logic as well
t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
y = y - (m<3)
day = (y + y/4 - y/100 + y/400 + t[m-1] + d)%7;
# from 0 to 6, weekdays
if day == 0:
print "Sunday"
elif day == 1:
print "Monday"
elif day == 2:
print "Tuesday"
elif day == 3:
print "Wednesday"
elif day == 4:
print "Thursday"
elif day == 5:
print "Friday"
elif day == 6:
print "Saturday"
答案 0 :(得分:1)
该程序将开始日期定为1700年1月1日星期五。它计算年,月和日的差异。抵消是这几个月的累积数字。对于Jan,不需要添加任何数字。仅添加0。对于2月,人们必须增加31天的1月,对于3月,一个人增加了31天的jan和28天的feb(总共59天)。等