简体   繁体   中英

Python Knapsack with Constraint by Type

Here is a simple knapsack problem that I took from the MIT open Course where I took from here .

The script optimizes for the weights and values, but I'd like it to optimize so there are no class repeats. So for example if I had a cap of 10, it would return w[0] v[0] c[0] and w[2] v[2] c[2] and NOT w[0] v[0] c[0] and w[1] v[1] c[1] and w[2] v[2] c[2]

weight= [5,3,2]
value = [9,7,8]
the_class = ["A","C","C"]
cap = 5

'''
w = the weight of item
v = the value of item
i = index of the item
aW = availible weight left (cap - w[i])
c = class of item
'''

def maxVal(w, v, i, aW,c): 
    if i == 0: 
        if w[i] <= aW: 
            return v[i] 
        else: 
            return 0 
    without_i = maxVal(w, v, i-1, aW, c) 
    if w[i] > aW: 
        return without_i 
    else: 
        with_i = v[i] + maxVal(w, v, i-1, aW - w[i], c) 

    return max(with_i, without_i)

res = maxVal(weight,value, len(value)-1, cap, the_class)
print "The result: ",res

Remove the unwanted items from the list first.

import itertools as it
from operator import itemgetter
weight= [5,3,2]
value = [9,7,8]
the_class = ["A","C","C"]
cap = 5

# define functions to sort with
classitem = itemgetter(0)
valueitem = itemgetter(1)
weightitem = itemgetter(2)

# combine the list elements to keep them together
classes = zip(the_class, value, weight)
classes.sort(key = classitem)

# use itertools.groupby() to aggregate the classes
for k, g in it.groupby(classes, classitem):
    things = list(g)
    print k, len(things)
    # remove the least valuable duplicates from the class list
    if len(things) > 1:
        things.sort(key = valueitem)
        for thing in things[:-1]:
            classes.remove(thing)

# reconstruct the original lists, sans unwanted duplicates
the_class = map(classitem, classes)
value = map(valueitem, classes)
weight = map(weightitem, classes)

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