Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I solve the leap year function in Python for Hackerrank?

Tags:

python

I cannot for the life of me solve this challenge on Hackerrank. The closest I got it was to 4/6 passes. Rules: In the Gregorian calendar three criteria must be taken into account to identify leap years:

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.

Code:

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

year = int(input())
print(is_leap(year))
like image 696
Charles Thompson Avatar asked Jun 08 '19 02:06

Charles Thompson


3 Answers

You forgot the ==0 or !=0 which will help understand the conditions better. You don't have to use them, but then it can cause confusion maintaining the code.

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

a shorter version would be:

def is_leap(year):
   return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
like image 169
DanielM Avatar answered Sep 18 '22 16:09

DanielM


You can try this

def is_leap():
    leap = False
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        leap = True
    return leap
like image 23
Shivam Suchak Avatar answered Sep 17 '22 16:09

Shivam Suchak


This code might be easy for some of the people to wrap their head around

def is_leap(year): leap = False

# Write your logic here
if year%4==0:
    leap=True
    if year%100==0:
        leap=False
        if year%400==0:
         leap=True

return leap

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

like image 26
Anshul Bisht Avatar answered Sep 17 '22 16:09

Anshul Bisht