HackerRank challenge write a function: Test case 1 failed

时间:2019-03-17 22:59:48

标签: python-3.x loops code-testing

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 个答案:

答案 0 :(得分:1)

问题在于,您只能测试y=int(x[-2:])的最后两位数字,实际上没有理由这样做。程序约束已经告诉您输入将是1900-10000之间的整数,因此您可以使用year。另外,您的return语句将在or之前对and进行求值(请参见here),因此它检查的最后一个内容将是!=100,因此将{{ 1}}。

答案 1 :(得分:0)

我不确定您的代码为什么不起作用,但是我有解决方案:

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

并对其进行测试:

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

此外,我不确定您在哪里运行该代码,但是问题确实要求输入 boolean 值(True或False),而您返回的是年份,所以这可能就是为什么您得到了错误。

答案 2 :(得分:0)

我喜欢您简洁的代码,用一行代码评估并返回结果! 但是,您的代码有两个问题: 1)您正在查看的最后两位数字而不是测试整数 2)逻辑评估顺序不正确。 试试这个简单的代码

schön

答案 3 :(得分: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