簡體   English   中英

誰能告訴我我的代碼有什么問題? 一個測試用例失敗

[英]Can anyone tell me what is wrong with my code? One test case is failing

def is_leap(year):
    leap = False
    
    # Write your logic here
    if year%4==0:
        return True
    elif year%400==0:
        return True
    elif year%100 != 0:
        return False
    else:
        return False
    return leap


year = int(input())
print(is_leap(year))

它表明一個測試用例失敗了。

注意順序。 您的代碼第二個條件year%400==0永遠無法達到,因為任何可以除以 400 的東西也可以除以 4。因此,400 的每個乘法都已經在year$4==0條件中被捕獲

def is_leap(year):
    if year % 400 == 0:
        return True
    if year % 100 == 0:
        return False
    if year % 4 == 0:
        return True
    return False

請記住,條件是按照它們寫入的順序進行評估的。

if year%4==0:
    return True

每年能被四整除的都是閏年...

elif year%400==0:
    return True

每年能被 400 整除的年也能被 4 整除,所以這個條件永遠不會被評估

elif year%100 != 0:
    return False

所有其他不能被 100 整除的年份都不是閏年。

else:
    return False

其他一切也不是閏年。

最后這兩個案例沒有意義; if condition: return False else: return False等同於return False

總之:你的條件相當於

if year%4==0:
    return True
else:
    return False

或者簡單地return year % 4 == 0
我希望你同意這是不正確的。

讓我們定義一個閏年。

如果 X 年是閏年

  • 它可以被四整除,
  • 除非它能被 100 整除,
  • 除非它能被 400 整除

那是,

return x % 4 == 0 and not (x % 100 == 0 and not (x % 400 == 0))

我們可以簡化,

return x % 4 == 0 and not (x % 100 == 0 and x % 400 != 0))

德摩根定律之一: not (a and b) == (not a) or (not b)

return x % 4 == 0 and (x % 100 != 0 or x % 400 == 0)

本質上,您按順序使用ifelif會使year%400==0變得多余。 if year%4==0將為真,測試條件停止。

我建議您從算法和流程圖開始,然后輸入 python 代碼。

那么,什么是閏年?
[Wikipedia,] integer 是 4 的倍數的年份(除了能被 100 整除但不能被 400 整除的年份)

回到你的代碼:需要測試!
注意條件周圍的括號以及and的使用
[更新:意識到我發布了錯誤的代碼片段]

# To write your logic here
# First, define leap year
### divisible by 4 and if divisible by 100, also divisible by 400
# Work out the logic and then write the code

def is_leap(year): 
    ## set leap default to false
    leap = False

    ## leap condition
    ## divisible by 4 except if divisible by 100 but not divisible by 400, return true (as leap year)
    ## the `and not` implies 'except'
    if (year%4 == 0) and not (year%400 != 0 and year%100 == 0):
        return True
    else:
        return False
    return leap

'''
## Note that we can follow the flowchart testing for 4, except (100 and not 400)
## Possible one-liner
    return (year % 4 == 0) and not (year % 100 == 0 and year % 400 != 0)
'''

year = int(input()) 
#year2 = 1900 #test
print(f'{year2} is leap year: {is_leap(year2)}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM