The task is classic knapsack problem. Greedy algorithm should be used in solvation. I managed to create code below, but it works too slow. Could you give me an idea how to speed it up? Thank you.
def backpack(c, array):
array.sort(key=lambda x: x[1])
array.sort(key=lambda x: x[0], reverse=True)
backpack = []
for item in array:
if item[1] <= c:
backpack.append(item)
c -= item[1]
result = []
for item in backpack:
result.append(item[2])
result.sort()
return print(*result)
c = int(input())
n = int(input())
array = list()
for i in range(n):
item = [int(x) for x in input().split()]
array.append(item)
array[i].append(i)
backpack(c, array)
c is weight limit for backpack. n represents the amount of price-weight pairs (both numbers have int type, not float). Restrictions are following: 1) should you choose between elements with the same weight, the one with the highest price should be taken 2) should you choose between elements with the same price and same weight, the one which was inputed first should be taken.