私は課題に取り組んでいますが、数行で理解できないエラーが発生し続けます
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」を渡すと停止し、「範囲外のインデックス」エラーが発生することです。
インクリメントメソッドを使用する代わりに、代わりに配列を編集しようとしました
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