2016-11-09 104 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