如何在 Python 中为 Hackerrank 解决闰年函数?

Cha*_*son 5 python

我一生都无法在 Hackerrank 上解决这个挑战。我得到的最接近的是 4/6 次传球。规则:在公历中,必须考虑三个标准来确定闰年:

The year can be evenly divided by 4, is a leap year, unless:
    The year can be evenly divided by 100, it is NOT a leap year, unless:
        The year is also evenly divisible by 400. Then it is a leap year.
Run Code Online (Sandbox Code Playgroud)

代码:

The year can be evenly divided by 4, is a leap year, unless:
    The year can be evenly divided by 100, it is NOT a leap year, unless:
        The year is also evenly divisible by 400. Then it is a leap year.
Run Code Online (Sandbox Code Playgroud)

Dan*_*elM 10

您忘记了==0!=0,这将有助于更好地理解条件。您不必使用它们,但它可能会导致维护代码的混乱。

def is_leap(year):
  leap = False

  if (year % 4 == 0) and (year % 100 != 0): 
      # Note that in your code the condition will be true if it is not..
      leap = True
  elif (year % 100 == 0) and (year % 400 != 0):
      leap = False
  elif (year % 400 == 0):
      # For some reason here you had False twice
      leap = True
  else:
      leap = False

  return leap
Run Code Online (Sandbox Code Playgroud)

一个较短的版本是:

def is_leap(year):
   return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Run Code Online (Sandbox Code Playgroud)