2016-11-09 69 views
0

我們知道這是一個閏年,如果它是被4整除,如果它是一個世紀以來,它被400整除我以爲我會需要兩個if語句是這樣的:確定閏年

def isLeap(n): 

if n % 100 == 0 and n % 400 == 0: 
    return True 
if n % 4 == 0: 
    return True 
else: 
    return False 

# Below is a set of tests so you can check if the code is correct. 

from test import testEqual 

testEqual(isLeap(1944), True) 
testEqual(isLeap(2011), False) 
testEqual(isLeap(1986), False) 
testEqual(isLeap(1956), True) 
testEqual(isLeap(1957), False) 
testEqual(isLeap(1800), False) 
testEqual(isLeap(1900), False) 
testEqual(isLeap(1600), True) 
testEqual(isLeap(2056), True) 

當我嘗試上面的代碼,我得到的錯誤消息年

1800 - Test Failed: expected False but got True 
1900 - Test Failed: expected False but got True 

基本上我需要我的代碼說,「如果今年四整除的測試結果是真,並且,如果它是一個世紀以來,它的整除400.」但是,當我嘗試:

if n % 4 and (n % 100 == 0 and n % 400 == 0): 
    return True 
else: 
    return False 

我得到三個錯誤消息(幾年)

1944 - Test Failed: expected True but got False 
1956 - Test Failed: expected True but got False 
2056 - Test Failed: expected True but got False 

因此,它看起來像我創造了第二個條件(由100和400整除)已經取消了年通過4

+1

你應該比較'如果n%4'的東西? –

+1

'n%100 == 0和n%400 == 0'是多餘的;如果它可以被400整除,它總會被100整除。想想你的數學有點難。 –

+2

順便說一句,[已經回答](https://stackoverflow.com/questions/11621740/how-to-determine-whether-a-year-is-a-leap-year-in-python?rq=1) –

回答

1

整除試試這個:

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

的問題是,你想要的t年如果是一個世紀的年份,可以被400或400整除。

>>> [(x % 100 != 0 and x % 4 == 0) or x % 400 == 0 for x in [1944, 1956, 2056, 1800, 1900]] 
[True, True, True, False, False] 
+2

1800年和1900年不是閏年 –

+0

是的,所以關鍵是用括號分隔括號中的兩個條件。謝謝。 – HappyHands31

+1

'(x%100 == 0 and x%400 == 0)'是多餘的。如果'x%400 == 0'爲真,則'x%100 == 0'也必須爲真。 – anregen

1

在本已經內置在評論中提到:calendar.isleap

你可以看到source here它只是:

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

寫出長篇是這樣的(多年> 1600):

def isLeapYear(year): 
    if year % 4 != 0: 
     return False 
    elif year % 100 != 0: 
     return True 
    elif year % 400 != 0: 
     return False 
    else: 
     return True 
1

這是一個較長的,可能較少混淆版本:

def isLeap(n): 
    if n % 4 == 0: 
     if n % 100 == 0: 
      if n % 400 == 0: 
       return True 
      return False 
     return True 
    return False