Skip to main content
 首页 » 编程设计

python之Checkio Python 列表拼图。索引超出范围错误

2024年11月01日8jirigala

这是checkIo时的问题描述-

"You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be (zero)."

结果应该是这样的-

if __name__ == '__main__': 
    assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30" 
    assert checkio([1, 3, 5]) == 30, "(1+5)*5=30" 
    assert checkio([6]) == 36, "(6)*6=36" 
    assert checkio([]) == 0, "Empty" 

这是我想出的-

def checkio(array): 
    total = sum(array[::2]) * array[-1] 
    return total 

它对前 3 个结果没有问题。最后一个给出断言错误,说索引超出范围。我无法解决这个问题。有可能我的整个代码都是错误的。但由于前三个是成功的,我不能说是不是。

最后,我不明白这是干什么的——

if __name__ == '__main__': 

请您参考如下方法:

你需要这样做:

def checkio(array): 
    if array: 
        return sum(array[::2]) * array[-1]  
    else: 
        return 0 

或者你可以把它放在一行中:

def checkio(array): 
    return sum(array[::2]) * array[-1] if array else 0 

至于

if __name__ == '__main__' 

我在这里有一个很好的答案:

What does if __name__ == "__main__": do?

但简而言之,__main__ 是您当前正在执行的顶级模块命名空间的名称,并且此代码只有在该顶级模块中时才会执行。在解释器中输入 __name__,它会返回同样的结果。或者在您正在执行的模块中,包括:

print('__name__ is: ', __name__ ) 

你会看到当你执行这个模块时,它会打印__main__。