1
的Lua移植的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 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)
遇到錯誤與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
'inSack [inSack + 1] =值[I]' 添加1〜'inSack'其應該是一個列表? 也許'inSack.append(values [i])'? :)另外,'in inack:'遍歷inSack元素。不是它的指數。 'in index,inSack:'代替。 – Kamiccolo
考慮到'i'是一個列表,那麼這個比較就沒有意義:'我<= 0'。 (請注意,在循環'for in inSack:'中,您實際上已經屏蔽了傳遞給'i'的原始項目) –
停止嘗試將Lua表用作Python列表...它們非常不同。 :P – Shashank