【问题标题】:Need help in finding the day of given (year,month,date) in python在 python 中查找给定日期(年、月、日)时需要帮助
【发布时间】:2020-12-29 11:22:59
【问题描述】:
def isYearLeap(year):   # Leap year formula

    if year % 4 == 0 and year % 100 != 0 :     
        return True 
    elif year % 400 == 0 :
        return True
    else :
        return False
    
            
testData = [1900, 2000, 2016, 1987]         # Test Data as reference

testResults = [False, True, True, False]

for i in range(len(testData)):

    yr = testData[i]
    print(yr,"->",end="")
    result = isYearLeap(yr)
    if result == testResults[i]:
        print("OK")
    else:
        print("Failed")

def daysInMonth(year, month): # Finding out days in months in common & leap year

    days = 0
    mo31 = [1,3,7,5,8,10,12]
    if year % 4 == 0 :              
        days = 1
        if year % 100 == 0 :
            days = 0
        if year % 400 == 0 :
            days = 1
    if month == 2 :
        return 28 + days
    if month in mo31 :
        return 31
    return 30

testYears = [1900, 2000, 2016, 1987] # Test Data as reference 

testMonths = [2, 2, 1, 11]
testResults = [28, 29, 31, 30]

for i in range(len(testYears)):

    yr = testYears[i]
    mo = testMonths[i]
    print(yr, mo, "->", end="")
    result = daysInMonth(yr, mo)
    if result == testResults[i]:
        print("OK")
    else:
        print("Failed")
        
def dayOfYear(year, month, day):

    doy = ["Sat","Sun","Mon","Tue","Wed","Thu","Fri"] # Days of week
    monthvalue = [1,4,4,0,2,5,0,3,6,1,4,6]        # Months value zellers rule
    century = [1700,1800,1900,2000]      # Zellers rule 
    value = [4,2,0,6]   # Zellers rule
    rem = 0     # Remainder Variable
    r = []      # Empty List to compare remainder and to a doy
    y = str(year)   # Converting year into string
    y = int(y[2:4]) # Taking last two digits of string & if used return the function ends 
    y = int(year)   # here returning last two digits 
    m = int(month)
    d = int(day)
    mo = [] # Empty list for comparing month with monthly values
    dd = 0   
    if dd == 0 :
        for i in range(len(monthvalue)) :
            mo.append(i)    # Creating mo list
            if m in mo:
                mo[i] == monthvalue[i]
        dd = y // 4 + d + m 
    if m >= 2 :                  
            dd -= 1
            dd += y
    for i in range(len(value)) :
        if y in century :
            y = century[i] == value[i]
            dd += y
            
    rem = dd % 7
    for i in range(len(doy)) :
        r.append(i) # Creating r list
        if rem in r :
            rem = r[i] == doy[i]
    print(rem)
        
    
        
print(dayOfYear(2000, 12, 31)) # Giving output False  "\n None

【问题讨论】:

  • 问题是什么?请阅读How to Ask 以及如何创建minimal reproducible example
  • 我是否必须假设这是一个练习,而您不允许 import datetimedate = datetime.datetime(2000, 12, 31)date.strftime("%m/%d/%Y, %A"),它们将返回:12/31/2000, Sunday
  • 这是 netacad cisco academy python course 的一项实验室工作,我在使用函数“def dayOfYear(year,month,day):”时遇到了问题,其中,“你的任务是编写和测试一个函数它接受三个参数(一年、一个月和一个月中的一天)并返回相应的一年中的一天,如果任何一个参数无效,则返回 None。上面的两个函数工作得很好,这些来自前面实验室,但本实验部分需要一些方法。它需要在“def dayOfYear(year,month,day):”函数之前定义这两个函数。

标签: python python-3.x


【解决方案1】:

您的代码包含许多不合逻辑的语句和冗余,使代码难以阅读/理解。 我建议首先查看一些样式指南或更基本的 Python 教程。

一些例子:

y = str(year)   # Converting year into string
y = int(y[2:4]) # Taking last two digits of string & if used return the function ends 
y = int(year)   # here returning last two digits

虽然前两个语句没有任何效果,但它们的 cmets 让我觉得你忘记了中间的两行代码。

dd = 0   
if dd == 0 :
    ...

如果检查永远不会评估为假,所以它是多余的

for i in range(len(monthvalue)) :
  mo.append(i)    # Creating mo list
  if m in mo:
     mo[i] == monthvalue[i]

mo 变量/列表不再使用

请检查您的程序流程并反馈

【讨论】:

  • 关于输出:False 来自rem = r[i] == doy[i],您最终将始终将some number == some weekday 分配给rem。由于您只打印它而不返回它,因此函数 dayOfYear 将返回 None,您在函数结束时打印它
  • 非常感谢我最后返回 doy[i] 的那一天,我只需要找出中间的一些计算错误,因为我需要取年份的最后两位数计算正确,正如你所说 y = str(year) & 接下来的两行没有任何效果我知道这一点,因为当我使用 return int(y[2:4]) 时,函数在那里结束&它只显示执行时年份的最后两位数字,函数的其余部分将被忽略。
【解决方案2】:

我认为这是 netacad cisco python 课程中的一个实验室。 您的任务是在 LAB 4.3.1.6 中创建 is_year_leap() 函数,在 LAB 4.3.1.7 中创建 days_in_month() 函数,在 LAB 4.3.1.8 中创建 day_of_year() 函数。这些函数分别有一个、两个、三个参数。请看下面的代码。请注意,如果任何参数无效,我排除了返回 None 的代码。我希望您自己将其添加为学习。

# from LAB 4.3.1.6
def is_year_leap(year):
    if year % 4 == 0:  # leap year occur every 4 years & is divisible by 4
        return True
    else:
        return False


# from LAB 4.3.1.7
def days_in_month(year, month):
    # Create list with month days for each month as advised in the LAB
    month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if is_year_leap(year):
        month_days[1] = 29  # 29 days for February on a leap year.
    return month_days[month - 1]  # month 1 corresponds with index 0 & so on.


# for LAB 4.3.1.8
def day_of_year(year, month, day):
    total = 0  # initializing the total variable to add results
    # create loop to add only days in the months before the month in the input/test data
    for i in range(1, month):
        result = days_in_month(year, i)
        total += result
    day_num = total + day  # add the value of the day argument to get day of the year
    return day_num


# test data
print(day_of_year(2000, 12, 31))
print(day_of_year(1999, 12, 31))
print(day_of_year(2021, 7, 29))

【讨论】:

    【解决方案3】:

    需要注意的一点是天数大于月的天数。

    def is_year_leap(year):
        return year % 4 == 0 and not year % 100 == 0 or year % 400 == 0
    
    
    def days_in_month(year, month):
        days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if is_year_leap(year):
            days[1] = 29
        return days[month - 1]
    
    
    def day_of_year(year, month, day):
        if day <= days_in_month(year, month):
            count = 0
            for yr in range(1, month):
                count += days_in_month(year, yr)
            return count + day
    

    【讨论】:

    • 嘿,navigos,请阅读how to format code,以便您的代码更容易理解
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多