Python 贪心小偷

-2 投票
2 回答
554 浏览
提问于 2025-04-17 21:51

为什么我运行程序时会出现“'int'对象不可下标索引”的错误?我检查了一下,觉得自己没有做错什么。我知道在第24行应该是一个整数,但当我把capacity[1]改成capacity(int[1])时,还是出现了同样的错误。有没有什么提示可以帮我?

class Bag():
    __slots__=('name', 'weight', 'value')

def mkBag(name, weight, value):
    thisBag = Bag()
    thisBag.name = name
    thisBag.weight = weight
    thisBag.value = value
    return thisBag

def ratio(treasure):
     print(treasure)
     print(treasure)
     return treasure[2]//treasure[1]

def plunder(treasure, capacity):
    treasure = sorted(treasure, key=ratio, reverse=True)
    bagLst = []
    current = 0
    while current < capacity:
        if capacity != 0:
            if capacity > current[1]:
                bagLst.append(mkBag(treasure[0],weight[1],current[2]))
                capacity = capacity - current[1]
            else:
                bagLst.append(mkBag(current[0], capacity, (current[2]/current[1]), capacity))
                capacity = 0
    return bagLst


def main():
    capacity = 10
    name = ''
    weight = 0
    value = 0
    treasure = [('silver', 20, 100), ('platinum', 10, 400), ('paladium',10,800), ('diamonds',5,900), ('gold', 10,60)]
    bagLst = plunder(treasure, capacity)

    for line in bagLst:
        print('bagLst')

2 个回答

0

"int" object not subscriptable 的意思是你在尝试用类似 1234[1] 的方式去访问一个整数。这是没有意义的!你可以对字符串(比如 'abcdefg'[1] == 'b')和列表(比如 [1,2,3,4,5][1] == 2)进行索引,但你不能从一个整数中获取“第n个元素”。

在你的代码行中:

# in def plunder(...):
if capacity > current[1]:

你试图访问 current 的第二个元素,但此时 current 的值是整数 0。你是想把它变成一个列表吗?你期待在 current[1] 中看到什么呢?

这里有一个更好的解决方案

你好,我想你是想说 current[1] 实际上应该是 item[1],也就是你正在查看的物品的重量。相反,current 是用来表示背包的当前重量。明白了!所以我写了一个更好的解决方案,看看吧!

class Treasure(object):
    def __init__(self,name,weight=0,value=0,id_=0):
        self.name = name
        self.weight = weight
        self.value = value
        self.id = id_ # bootstrap for further development
    @property
    def ratio(self):
        return self.value/self.weight

class BagFullError(ValueError):
    pass

class Bag(object):
    def __init__(self,owner=None,capacity=10):
        self.owner = owner
        self.capacity = capacity
        self.contents = list()
    def __str__(self):
        return_value = "CONTENTS:"
        for item in self.contents:
            return_value += "\n  ${0.value:4}  {0.name:10}{0.weight} lb".format(item)
        return return_value
    def add(self,other):
        if not isinstance(other,Treasure):
            raise TypeError("Must pick up Treasure")
        if self.weight + other.weight > self.capacity:
            raise BagFullError("Bag cannot fit {}({} lb) ({} lb/{} lb)".format(
                other.name,other.weight,self.weight,self.capacity))
        self.contents.append(other)
    def remove(self,other):
        self.contents.remove(other)
        # may throw ValueError if `other` not in `self.contents`
    @property
    def weight(self):
        return sum(item.weight for item in self.contents)

treasure = [Treasure('silver', 20, 100), Treasure('platinum', 10, 400),
            Treasure('paladium',10,800), Treasure('diamonds',5,900),
            Treasure('gold', 10,60)]
## map(lambda x: Treasure(*x), [('silver',20,100), ... ])

def plunder(treasure_list,bag=None):
    _bag = bag or Bag()
    treasures = sorted(treasure_list,
                       key = lambda x: x.ratio,
                       reverse = True)
    while True:
        for treasure in treasures:
            try: _bag.add(treasure)
            except BagFullError as e:
                print(e)
                return _bag

bag = Bag("Adam",100)
print(bag)
plunder(treasure,bag)
print(bag)
print("Total Value: {}".format(sum(item.value for item in bag.contents)))
2

current 是一个整数:

current = 0

但是你却想把它当成一个列表来用:

if capacity > current[1]:
    bagLst.append(mkBag(treasure[0],weight[1],current[2]))
    capacity = capacity - current[1]
else:
    bagLst.append(mkBag(current[0], capacity, (current[2]/current[1]), capacity))

每次你使用 current[index] 的时候,其实是在尝试用一个索引去访问这个整数的值。

如果你希望 current 是一个序列(像列表那样),那么你需要把它设置成一个序列。

猜测你是想查看当前的宝藏,以便把它放进背包;不过你并没有选择任何宝藏物品。可以参考下面的代码:

current = 0

while capacity and current < len(treasure):
    item = treasure[current]
    current += 1
    if capacity > item[1]:
        bagLst.append(mkBag(item[0], item[1], item[2]))
        capacity = capacity - item[1]
    else:
        bagLst.append(mkBag(item[0], capacity, (item[2]/item[1]), capacity))
        capacity = 0

撰写回答