从一年中的天数中获取一天?

时间:2019-05-24 18:14:22

标签: python algorithm datetime

如何编写一个程序来询问用户一年中2到365之间的天数,并询问一年中的第一天-  星期日,星期一或星期二等。然后程序应显示已输入的天数。

例如:

Input year = 2019

Input of day number = 144

First day of year = 'Tuesday'

Output = 'Friday' (-> 144th day of year 2019 = Friday)

注意:-您不能使用该特定年份的“日期”和“月份”

从算法的link中,我试图以此作为参考来找出一天,但找不到特定的解决方案:

def day_of_week(year, month, day):
    t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
    year -= month < 3
    return (year + int(year/4) - int(year/100) + int(year/400) + t[month-1] 
            + day) % 7

day = 28

month = 4

year = 2019


print(day_of_week(year, month, day))

2 个答案:

答案 0 :(得分:0)

让我们看看我是否理解正确……该程序采用年份,一年中的第一天(例如“星期二”)和数字(例如144),并且只输出对应的星期几到一年中的那个天(例如“星期五是2019年的第144天”)?

如果这是问题所在,只需使用mod by 7来找到答案,就像这样:

def numberedDay(firstDay, dayNumber):
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    firstIndex = days.index(firstDay)
    endIndex = (firstIndex + int(dayNumber) - 1) % 7
    return days[endIndex]


year = input("Year: ")
firstDay = input("First day of the year (e.g. 'Monday'): ")
dayNumber = input("Day number: ")

print(numberedDay(firstDay, dayNumber))

答案 1 :(得分:0)

但是根据'dayNumber'的条件,它应该在2到365之间。我认为这可能是可行的...

# Solution - 2 With dayNumber in the Range betwwen 2 to 365...


import sys
def numberedDay(firstDay, dayNumber):
   #firstDay = 'Wednesday'
   #dayNumber = 319

   # Made weekly days dictionary 
   days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 
   'Sunday']
   # Automatically generate first index of days dictionary.. For example if firstDay 
   = 'Wednesday' then it will return firstDay=2
   firstIndex = days.index(firstDay)
   # Generating endIndex....
   endIndex = (firstIndex + int(dayNumber) - 1) % 7
   # endIndex = (2 + int(dayNumber) - 1) % 7
   # endIndex = (2 + 319 - 1) % 7
   # endIndex = (320) % 7
   # endIndex =  5

   return days[endIndex]
   # return 5th element of days list which is = Saturday

# Input Year = 1997
year = input("Year: ")
# Input firstDay = Wednesday
firstDay = input("First day of the year (e.g. 'Monday'): ")
# Input dayNumber = 319
dayNumber = input("Day number: ")

#if int(dayNumber) > 365:
#    raise sys.exit()


if int(dayNumber) in range(2,365): 
   # printing dayNumber given by user
   dayNumber = int(dayNumber)

else:
   # if dayNumber is greater than 365 then system will be exit.
   raise sys.exit()

# printing output
print(numberedDay(firstDay, dayNumber))