3

所以我必须解决课堂上的背包问题。到目前为止,我已经想出了以下内容。我的比较器是确定两个主题中哪一个是更好选择的函数(通过查看相应的 (value,work) 元组)。

我决定迭代工作少于 maxWork 的可能主题,为了找到在任何给定轮次中哪个主题是最佳选择,我将我最近的主题与我们尚未使用的所有其他主题进行了比较。

def greedyAdvisor(subjects, maxWork, comparator):
    """
    Returns a dictionary mapping subject name to (value, work) which includes
    subjects selected by the algorithm, such that the total work of subjects in
    the dictionary is not greater than maxWork.  The subjects are chosen using
    a greedy algorithm.  The subjects dictionary should not be mutated.

    subjects: dictionary mapping subject name to (value, work)
    maxWork: int >= 0
    comparator: function taking two tuples and returning a bool
    returns: dictionary mapping subject name to (value, work)
    """

    optimal = {}
    while maxWork > 0:
        new_subjects = dict((k,v) for k,v in subjects.items() if v[1] < maxWork)
        key_list = new_subjects.keys()
        for name in new_subjects:
            #create a truncated dictionary
            new_subjects = dict((name, new_subjects.get(name)) for name in key_list)
            key_list.remove(name)
            #compare over the entire dictionary
            if reduce(comparator,new_subjects.values())==True:
                #insert this name into the optimal dictionary
                optimal[name] = new_subjects[name]
                #update maxWork
                maxWork = maxWork - subjects[name][1]
                #and restart the while loop with maxWork updated
                break
    return optimal  

问题是我不知道为什么这是错误的。我遇到了错误,我不知道我的代码哪里出错了(即使在输入打印语句之后)。帮助将不胜感激,谢谢!

4

2 回答 2

4

与 OPT 相比,使用简单的贪心算法不会对解决方案的质量产生任何限制。

这是背包的完全多项式时间(1 - epsilon)* OPT 近似伪代码:

items = [...]  # items
profit = {...} # this needs to be the profit for each item
sizes = {...}  # this needs to be the sizes of each item
epsilon = 0.1  # you can adjust this to be arbitrarily small
P = max(items) # maximum profit of the list of items
K = (epsilon * P) / float(len(items))
for item in items:
    profit[item] = math.floor(profit[item] / K)
return _most_prof_set(items, sizes, profit, P)

我们现在需要定义最有利可图的集合算法。我们可以通过一些动态规划来做到这一点。但首先让我们回顾一些定义。

如果 P 是集合中最有利可图的项目,n 是我们拥有的项目数量,那么 nP 显然是允许利润的一个微不足道的上限。对于 {1,...,n} 中的每个 i 和 {1,...,nP} 中的 p,我们让 Sip 表示其总利润恰好为p 且总规模最小的项目子集。然后我们让 A(i,p) 表示集合 Sip 的大小(如果不存在则为无穷大)。我们可以很容易地证明 A(1,p) 对于 {1,...,nP} 中的所有 p 值都是已知的。我们将定义一个递归来计算我们将用作动态规划问题的 A(i,p),以返回近似解。

A(i + 1, p) = min {A(i,p), size(item at i + 1 position) + A(i, p - profit(item at i + 1 position))} if profit(item at i + 1) < p otherwise A(i,p)

最后我们给 _most_prof_set

def _most_prof_set(items, sizes, profit, P):
    A = {...}
    for i in range(len(items) - 1):
        item = items[i+1]
        oitem = items[i]
        for p in [P * k for k in range(1,i+1)]:
            if profit[item] < p:
                A[(item,p)] = min([A[(oitem,p)], \
                                     sizes[item] + A[(item, p - profit[item])]])
            else:
                A[(item,p)] = A[(oitem,p)] if (oitem,p) in A else sys.maxint
    return max(A) 

来源

于 2011-04-15T23:31:00.687 回答
0
def swap(a,b):
    return b,a

def sort_in_decreasing_order_of_profit(ratio,weight,profit):
    for i in range(0,len(weight)):
        for j in range(i+1,len(weight)) :
            if(ratio[i]<ratio[j]):
                ratio[i],ratio[j]=swap(ratio[i],ratio[j])
                weight[i],weight[j]=swap(weight[i],weight[j])
                profit[i],profit[j]=swap(profit[i],profit[j])
    return ratio,weight,profit          
def knapsack(m,i,weight,profit,newpr):

    if(i<len(weight) and m>0):
        if(m>weight[i]):
            newpr+=profit[i]
        else:
            newpr+=(m/weight[i])*profit[i]  
        newpr=knapsack(m-weight[i],i+1,weight,profit,newpr)
    return newpr
def printing_in_tabular_form(ratio,weight,profit):

    print(" WEIGHT\tPROFIT\t RATIO")
    for i in range(0,len(ratio)):
        print ('{}\t{} \t {}'.format(weight[i],profit[i],ratio[i]))

weight=[10.0,10.0,18.0]
profit=[24.0,15.0,25.0]
ratio=[]
for i in range(0,len(weight)):
    ratio.append((profit[i])/weight[i])
#caling function
ratio,weight,profit=sort_in_decreasing_order_of_profit(ratio,weight,profit) 
printing_in_tabular_form(ratio,weight,profit)

newpr=0
newpr=knapsack(20.0,0,weight,profit,newpr)          
print("Profit earned=",newpr)
于 2017-05-27T12:05:46.213 回答