简体   繁体   中英

Python remove tuples based on tuple values

I'd like to return the tuples so that they add up to 400 in weight, but also there should be no repeating classes.

So the optimal solution for below would be (items, weight<400,max values, no repeating classes so 1a,1e,1g,1b)

#mytuple = (item, weight, value, class)
mytuple= (('map', 9, 150, 'a'), ('compass', 13, 35, 'a'), ('water', 153, 200, 'a'), ('sandwich', 50, 160, 'a'), ('glucose', 15, 60, 'e'), ('banana', 27, 60, 'g'), ('suntan cream', 11, 70, 'a'), ('waterproof trousers', 42, 70, 'e'), ('waterproof overclothes', 43, 75, 'a'), ('note-case', 22, 80, 'a'), ('sunglasses', 7, 20, 'b'), ('socks', 4, 50, 'a'))

You may want to consider using a set or a dictionary (with the class as the key), not a tuple of tuples. They're much easier to manipulate.

The problem itself is the knapsack problem, which is a classic piece of computer science, and exhaustively documented on the internet at large.

The easiest (but often inaccurate accurate) solution is a greedy algorithm, but since this is almost certainly a homework problem, you want the dynamic programming solution- because this is the canonical introduction to dynamic programming. This is a pretty good overview , with readable psuedocode and a pretty table.

Here's how you remove elements from a list:

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a.pop()  #remove & return the right-most element
3
>>> a
[1, 2]
>>> a.pop(0) #remove & return element at given index
1
>>> a
[2]

As for your problem, it's a variant of the bin packing problem and it's NP-hard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM