将 Lua 移植到 Python 中。

values = {1, 2, 3, 4, 5, 6, 7, 8, 9};
inSack = {}
total  = 0;
function knapsack(i, weight)
        if weight == 0 then
                print("Success The following combination is in the knapsack:");
                for i = 1, #inSack do
                        total = total + inSack[i];
                        print(inSack[i]);
                end
                print("Totaling to Input of: "..total)
                return
        elseif i <= 0 then
                print("Sorry your weight combination, is not possible with the current values ");
                return;
        end
        if values[i] > weight then
                return knapsack(i-1, weight);
        else
                inSack[#inSack + 1] = values[i];
                return knapsack(i-1, weight - values[i]);
        end

end
-- Waits for user input to terminal
local number = io.read()
knapsack(#values, tonumber(number));

我的 Python 代码:

values = [1,2,3,4,5,6,7,8,9]
inSack = []
total = 0

def knapsack(i, weight):
    if weight == 0:
        print("success: ")
        for item in inSack:
            total = total + item
            print(item)
        print("totaling to input of: "+ str(total))
        return
    elif i <= 0:
        print("didn't work yo")
        return
    if values[i-1] > weight:
        return knapsack(i-1, weight)
    else:
        inSack.append(values[i-1])
        return knapsack(i-1, weight - values[i-1])

number = input("Enter a number: ")
knapsack(len(values), int(number))

我在将 "if values[i]>weight" 语句移植到 Python 中时出现了错误。我的错误是什么?

跟踪记录:

Traceback (most recent call last):
  File "lua.py", line 23, in <module>
    knapsack(values, number)
  File "lua.py", line 16, in knapsack
    if values[i] > weight:
TypeError: list indices must be integers, not list
点赞
用户1763614
用户1763614

我猜你最后漏掉了一个 len();相当于 Python 中的

knapsack(#values, tonumber(number));

应该改为

knapsack(len(values), number)
2013-10-16 17:18:32