2013-10-17 1 views
0

여기 NIT에서 가져온 간단한 배낭 문제는 here에서 가져 왔습니다.타입 별 구속 조건이있는 Python 배낭

스크립트는 가중치와 값을 최적화하지만 클래스 반복이 없도록 스크립트를 최적화하고 싶습니다. 나는 10의 모자를 가지고 예를 들어 그래서, 그것은 w[0] v[0] c[0] and w[2] v[2] c[2]을 반환하고 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 
+0

* 반복 * 제작하지 않아야합니까? 클래스 "C"는 가중치가 2이고 값은 "C"/ 7/3과 같은 클래스입니까? 데이터에서 잘못된 값을 제거하는 것이 더 나을 수도 있습니다. – wwii

+0

@wwii 예 그들은 같은 클래스입니다. 하지만 각 수업 중 1 과목 만 수강 할 수있는 프로그램이 필요합니다. – user2758113

+0

어떤 것을 가져갈 지 어떻게 압니까? 또는 중요합니까 - 그냥 가져 가세요? – wwii

답변

0

먼저 목록에서 불필요한 항목을 제거합니다.

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) 
+0

무게, 값 및 클래스 목록의 크기가 다양하기 때문에이 기능이 작동하지 않습니다. – user2758113

+0

당신은'''''(the_class)! = len (weight)! = len (values)'''라고 말하고 있습니까? 이것은 임의의 길이의 목록에 대해 작동해야합니다. 세 개의 목록이 동일한 길이라고 가정합니다. 길이가 다른 경우 세 가지 목록이 맞지 않을 것입니다. 너 해봤 니? – wwii