背包:从列表中添加项目(Python)

时间:2015-02-25 03:20:23

标签: python-3.x knapsack-problem

我正在尝试为背包问题编写代码。哪里有一个重量容量的背包,你选择一个项目的组合,以找到最好的解决方案。我试图随机生成可能的解决方案。因此,我的代码将选择一个随机数量的随机项(生成随机大小的列表)并测试以确定解决方案是否可行(小于容量)或不可行(大于容量)。但是,当我尝试将总重量和所有项目的总价值相加时,该数字将关闭。比方说,这是每个项目的数据。

Itms    Wts     Vals   
=====================
1       22      80
2       29      35
3       12      36
4       14      24
5       29      41
6       30      87
7       18      10
8       22      63
9       12      66

10 27 72

这是运行代码后的结果:

Items picked:  [6, 4, 1, 7, 8, 3]
Feasible:  Total Wt =  18 Total Val =  10
Items picked:  [1]
Infeasible:  Total Wt =  135 Total Val =  264
Items picked:  [5, 1, 8, 6, 7, 4]
Infeasible:  Total Wt =  89 Total Val =  198

因此值不正确。但我不知道我的代码中有什么问题:

def genSoln(cap,items):
    g = input("Would you like to generate random potential solutions? [y/n] ")
    if g == 'y':
        gen = int(input("Number of times to generate/check random potential solutions? "))
        totalwt = 0
        totalval = 0
        for i in range(1,gen+1):
            pop = range(1,items)
            leng = random.randint(1,len(pop))
            ran = random.sample(pop, leng)
            for i in ran:
                totalwt += int(wts[i])
                totalval += int(vals[i])
                if i == len(ran):
                    if totalwt < int(cap):
                        print("Items picked: ", ran)
                        print("Feasible: ", "Total Wt = ", totalwt, "Total Val = ", totalval)
                    else:
                        print("Items picked: ", ran)
                        print("Infeasible: ", "Total Wt = ", totalwt, "Total Val = ", totalval)
                    totalwt = 0
                    totalval = 0

1 个答案:

答案 0 :(得分:0)

没关系。我自己想出了答案。我只需要取出if i == len(ran):,将totalwttotalval移到for循环(for i in range(1,gen+1))中,并在添加到totalwt时从i中减1 totalval

def genSoln(cap,items):
    g = input("Would you like to generate random potential solutions? [y/n] ")
    if g == 'y':
        gen = int(input("Number of times to generate/check random potential solutions? "))
        for i in range(1,gen+1):
            totalwt = 0
            totalval = 0
            pop = range(1,items)
            leng = random.randint(1,len(pop))
            ran = random.sample(pop, leng)
            for i in ran:
                totalwt += int(wts[i-1])
                totalval += int(vals[i-1])
            if totalwt < int(cap):
                print("Items picked: ", ran)
                print("Feasible: ", "Total Wt = ", totalwt, "Total Val = ", totalval)
            else:
                print("Items picked: ", ran)
                print("Infeasible: ", "Total Wt = ", totalwt, "Total Val = ", totalval)
相关问题