python - 列表索引越界和堆栈溢出错误

标签 python stack-overflow indexoutofboundsexception

这次我试图使用 python 获得最大成对乘积,某些方面的概念对我来说仍然是新的。我继续收到列表索引越界错误和堆栈溢出,鉴于我无法在 Python 中选择类型,我不知道如何处理这些错误。

我研究了 enumerate 和其他 iterate(ble) 函数,但没有结果。我的回答可以帮助 future 的人们解决从 C 迁移到 python 时的简单 for 循环问题。

def max_pairwise_product(numbers):
    n = len(numbers)
    max_product = 0
    for first in range(n):
        for second in range(first + 1, n):
            max_product = max(max_product,
                numbers[first] * numbers[second])

    return max_product

def max_pairwise_product_fast(numbers):
    n = len(numbers)
    index1 = 1
    for i in range(2,n,1):
        if (numbers[i]>numbers[index1]):
            index1 = i
    if (index1 == 1):
        index2 = 2
    else:
        index2=1
    for i in range(1,n):
        if(numbers[i]!=numbers[index1] and numbers[i]>numbers[index2]):
            index2 = i
    return (numbers[index1]*numbers[index2])
if __name__ == '__main__':
    input_n = int(input())
    input_numbers = [int(x) for x in input().split()]
    print(max_pairwise_product_fast(input_numbers))
Traceback (most recent call last):
  File "C:/Users/Tevin/.PyCharmCE2018.3/config/scratches/scratch_1.py", line 31, in <module>
    print(max_pairwise_product_fast(input_numbers))
  File "C:/Users/Tevin/.PyCharmCE2018.3/config/scratches/scratch_1.py", line 27, in max_pairwise_product_fast
    return (numbers[index1]*numbers[index2])
IndexError: list index out of range

最佳答案

为什么不在列表中找到 2 个最大数字并将它们相乘以获得最大乘积。找到列表的最大值然后将其保存在某个变量中。将其从列表中删除并再次查找最大值。然后将其与您保存的变量相乘。

至于你的代码,这一行是做什么用的?

input_n = int(input())

您没有在任何地方使用 input_n 变量。

和行:

input_numbers = [int(x) for x in input().split()]

您的代码将要求您提供 2 个输入。当您第一次输入输入内容时,它会保存在 input_n 变量中。然后您的第二个输入将保存为 input_numbers。您为程序提供的输入类型有问题。

关于python - 列表索引越界和堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695321/

相关文章:

java - ArrayIndexOutOfBound异常该如何处理?

c# - 分配引用类型时 c# 中的奇怪 stackoverflow

python - Numpy:获取一维数组元素的索引作为二维数组

python - DRF oneToOneField 创建序列化器

python - 如何在 Django Admin 中更改 ForeignKey 显示文本?

android - 在 eclipce 中打开 XML 文件时出现 StackOverflowError

java - 声明类会导致 StackOverflow 错误

java - 从SQLite数据库删除项目时出错

Java ArrayList 抛出 IndexOutOfBoundsException。为什么?

python - 如何从列表中的函数输出访问元素?