1

this is my code for the hackerRank challenge write a function

def is_leap(year):
    x=str(year)
    y=int(x[-2:])

    return y%4==0 or y%400==0 and y%100!=0


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

All 5 test cases worked except for one, when year=2100, and I'd like to know why? what's wrong with my code? edit: after running the code I got the following:

Compiler Message: Wrong Answer

Input (stdin): 2100

Expected Output: False

4 Answers4

1

The problem is you only test on the last two digits, as seen by y=int(x[-2:]), which there's really no reason to. The program constraints already tell you the input will be an int from 1900-10000, so you can just work with year. Also, your return statement will evaluate the or before the and (See here), so the last thing it checks will be !=100, thus breaking it for the 400 case.

  • Right explanation. As a remark, one correct possibility of writing the logical expression could be: `(y% 4 == 0 and y % 100 != 0) or y % 400 == 0` – FlorianDe Mar 17 '19 at 23:35
0

I'm not exactly sure why your code doesn't work, but I have the solution:

def is_leap(year):
    if year%4 == 0:
        if year%100 == 0:
            if year%400 == 0:
                return True #divisible by 4, divisible by 100, and divisible by 400
            else:
                return False #divisible by 4 and divisible by 100
        else:
            return True #divisible by 4 and not divisible by 100
    else:
        return False #not divisible by 4

And to test it:

for i in range(1000, 2501, 4):
    if not is_leap(i):
        print(str(i)) # this will print all the "irregular" leap years between 1000 and 2500

Also, I'm not sure where you are running that code, but the question does ask for boolean values (True or False) and you are returning the years instead, so that might be why you are getting the error.

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
0

I like your concise code of evaluating and returning result in one line of code! However, two issues with your code: 1) You are looking at the last two digits instead of testing the whole number 2) The logical evaluation order is incorrect. Try this simple code

def is_leap(year):
    y=int(year)
    return  y%400==0 or (y%100 != 0 and y%4==0)
year = input()
print(is_leap(year))
0
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
Michael
  • 3,093
  • 7
  • 39
  • 83
tanmaychk
  • 37
  • 5