Home > database >  Programm stops working with large numbers
Programm stops working with large numbers

Time:03-26

I created a wonderful code that, taking into account the maximum allowable weight of a backpack, returns the items from the list by repeated enumeration, sums up their price and weight, and gives the result. At the moment, I am facing the problem that the code simply does not run when the maximum weight becomes large (for example 80). I don't really understand if this is a problem with infinite loops or optimization, so I would appreciate your help with it!

backpack_max = int(input('Backpack limit: '))
item_list = ['Rune', 'Arrows', 'Rock', 'Sword']
item_weight = [2, 4, 5, 10]
item_price = [20, 4, 1, 15]
backpack_fin_items = []
total_weight = 0
total_price = 0
count = 0

while total_weight min(item_weight) < backpack_max:
  for item, price in zip(item_list, item_price):
    if total_weight item_weight[count] <= backpack_max:
      total_weight  = item_weight[count]
      backpack_fin_items.append(item.lower())
      total_price  = price
      count  = 1
      count %= len(item_list)
      joint = ', '.join(backpack_fin_items)
  
print (f'You are packed with loot! \n\nContent: {joint}\n\nTotal weight: {total_weight}/{backpack_max} kg\nTotal price: {total_price} coins\n\nHave a nice adventure, warrior!')

CodePudding user response:

It's not that you have too many items, it's that you get stuck in a state where you're unable to add any items to the backpack. To debug small programs like this, a helpful thing is to stick a print in the part of the code that's doing something you don't expect.

while total_weight min(item_weight) < backpack_max:
    print(total_weight, backpack_fin_items)
    # ...

prints this in an infinite loop:

74 ['rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock']
74 ['rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock', 'sword', 'rune', 'arrows', 'rock']

which is not intuitive, since it seems like we should be able to add items of weight 2.

Looking more closely at the code:

    for item, price in zip(item_list, item_price):
        if total_weight item_weight[count] <= backpack_max:

I suspect the problem is with item_weight[count] -- it's not clear to me how that would get you the weight associated with item, or what count is supposed to be doing.

If I just add the weights to your zip expression and delete all the lines that reference count otherwise, it works fine:

    for item, price, weight in zip(item_list, item_price, item_weight):
        if total_weight   weight <= backpack_max:
            total_weight  = weight
  • Related