我正在做一项任务,但几行代码不断给我错误,我无法理解
pick=0
final=0
while True:
if (min_weight>0):
if (sort_ratio[pick]["Weight"]<min_weight):
final = final + sort_ratio[pick]["Cost"]
min_weight = min_weight - sort_ratio[pick]["Weight"]
if (sort_ratio[pick]["Weight"]>min_weight):
pick = pick + 1
if (min_weight == 0):
print (final)
return
唯一的问题是当程序通过“pick = pick+ 1”时它会停止并给出“index out of range”错误。
我没有使用增量方法,而是尝试编辑数组而不是使用
sort_ratio.remove(sort_ratio[0]);
但它给了我“不能解释为整数问题”
当前代码
from operator import itemgetter
import math
raw_input=input;
test_case = int(raw_input());
for inp1 in range (test_case):
min_weight = int(raw_input());
candy_types = int(raw_input());
candy = [];
for inp2 in range (candy_types):
can_weight,can_cost = map(int,raw_input().split());
ratio_candy = (can_cost / int(can_weight));
candy.extend([{"Cost": can_cost, "Ratio": ratio_candy, "Weight": can_weight}]);
sort_ratio = sorted ( candy, key=itemgetter('Ratio'));
pick = 0;
final = 0;
while True:
if (min_weight>0):
if (sort_ratio[pick]["Weight"]<min_weight):
final = final + sort_ratio[pick]["Cost"]
min_weight = min_weight - sort_ratio[pick]["Weight"]
print (final)
print (min_weight)
if (sort_ratio[pick]["Weight"]>min_weight):
pick = pick + 1
if (min_weight==0):
print (final)
break