将Lua移植到Python

时间:2013-10-16 16:36:22

标签: python lua porting

Lua

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 i in inSack:
            total = total +inSack[i]
            print(inSack[i])
        print("totaling to input of: "+total)
        return
    elif i<= 0:
        print("didn't work yo")
        return
    if values[i] > weight:
        return knapsack(i-1, weight)
    else:
        inSack[inSack+1] = values[i]
        return knapsack(i-1, weight - values[i])

number = raw_input("Enter a number: ")
knapsack(values, number)

我收到了移植到python的if values[i] > weight语句的错误。我犯的错误是什么?

回溯

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

1 个答案:

答案 0 :(得分:2)

我猜你最后错过了len();

的Python等价物
knapsack(#values, tonumber(number));

将是

knapsack(len(values), number)
相关问题