Python代码中的IndexError

时间:2015-02-17 19:06:43

标签: list python-3.x indexing

我的代码应该评估背包问题的解决方案。 Wts是一个列表。我会包含整个代码,但它真的很长。我遇到了这个问题:

totalwt += int(wts[i])
IndexError: list index out of range

但这是代码:

ev = input("Do you want to evaluate a potential solution? [y/n] ")
chosen = []
totalwt = 0
totalval = 0

if ev == 'y':
    print("Please enter a potential solution.")
    n = True
    while n == True:
        sol = int(input("Enter id [1..{0}] of item to be picked, or 0 when done. ".format(items)))
        if int(sol) >= 1 and int(sol) <= items:
            chosen.append(sol)
        else:
            n = False
    for i in chosen:
        totalwt += int(wts[i])
        totalval += int(vals[i])
    if totalwt < int(cap):
        print("Feasible: ","Total Wt = ",totalwt,"Total Val = ",totalval)
    else:
        print("Infeasible: ","Total Wt = ",totalwt,"Total Val = ",totalval)
elif ev == 'n':
    print("Okay. You are done. Thank you!")

我没有看到问题所在。但如果需要更多代码,我将很乐意提供它。

1 个答案:

答案 0 :(得分:1)

根据您的代码,我假设items是一个表示wts长度的整数。

如果是这样,您将需要更改此代码:

if int(sol) >= 1 and int(sol) <= items:
    chosen.append(sol)

到此:

if sol >= 1 and sol <= items:
    chosen.append(sol-1)

请注意,这是因为列表索引从0开始,而不是1。