尝试解决hacker rank问题,仍然是初学者,我不知道在Python 3中出了什么错误。

2024-09-29 20:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是: 给定一个整数数组,查找并打印可从数组中选择的最大整数数,以使所选整数中任意两个的绝对差小于或等于1

def pickingNumbers(a):
    maxi=0
    for i in a:
        x=a.count(i)
        y=a.count(i-1)
        x=x+y
        if x>maxi :
            maxi=x
    print(maxi)     
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())
    a = list(map(int, input().rstrip().split()))

    result = pickingNumbers(a)

    fptr.write(str(result) + '\n')

    fptr.close()

给定输入:

6
4 6 5 3 3 1

预期输出:3

我的输出:None


Tags: nameinforinputifdefcount整数
1条回答
网友
1楼 · 发布于 2024-09-29 20:15:43

pickingNumbers的末尾打印maxi的值,而不是返回它

由于没有显式返回值,因此函数返回None,该值被转换为str(result)中的字符串'None'

只需更换:

def pickingNumbers(a):
    maxi = 0
    for i in a:
        x = a.count(i)
        y = a.count(i-1)
        x = x+y
        if x > maxi :
            maxi = x
    return maxi

你应该没事的

相关问题 更多 >

    热门问题