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

标签 python

这是 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?

但短期的类(class)是,__main__ 是您当前正在执行的顶级模块命名空间的名称,并且此代码仅在该顶级模块中时才会执行。在解释器中输入 __name__ ,它将返回相同的结果。或者在您正在执行的模块中,包括:

print('__name__ is: ', __name__ )

你会看到当你执行该模块时,它将打印 __main__

关于python - Checkio Python 列表拼图。索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22536199/

相关文章:

python - 当我尝试执行sql查询时出现错误

python - 数据库中的 Pyramid 国际化 i18n 单词?

Python 输出参数?

python - 在 mongoengine EmbeddedDocumentListField 中分组

python - 在同一个图上使用 Matplotlib 和 Pandas 绘制图

python - 使用 DBSCAN 聚类 word2vec 输出的故障排除技巧

python - bash中无法识别的命令被python解释器捕获

python - Pandas 数据框的最大值和最小值

python - Python 中的网页抓取

python - 包含列表的 Pandas 列的 get_dummies