python访问数组错误

2024-04-19 14:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一项作业,但这几行字不断地给我错误,我不能理解

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”时,它停止并给出“索引超出范围”错误

我没有使用increment方法,而是尝试使用

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

Tags: inputrawifminsortcanfinalint