01背包问题的python代码实现与算法比较

本文介绍了01背包问题的三种贪婪算法实现:价值贪婪、时间贪婪和价时比贪婪,并通过代码展示了它们的运行过程。同时,对比了动态规划的二维表法解决01背包问题,结果显示贪婪算法无法得到最优解,而动态规划能获得更高价值。动态规划算法通过二维表格动态更新,能够找到最大价值组合。
摘要由CSDN通过智能技术生成

01背包问题的代码实现与算法比较

01背包问题

关于01背包问题的具体描述可以参考0-1背包问题的动态规划算法-by Liu言杂记

事实上,我今天的内容就是对上述文章的部分代码实现及算法比较。

贪婪算法与其无法得到最优解的证明

我将这个问题的贪婪算法实现的分为三种:

  • 价值-贪婪
  • 时间贪婪
  • 时价比贪婪(价时比指的是价值与时间的比值)
    实现如下:
def value_greedy(n, time):
    '''价值贪婪算法'''
    route = []  #存储需要抢夺的礼物下标
    v_sort = sorted(enumerate(v), key=lambda x: x[1])
    new_idx = [i[0] for i in v_sort]
    new_v = [i[1] for i in v_sort]
    new_t = [t[i] for i in new_idx]
    while time >= new_t[0]:
        idx = 0
        while idx < n - 1 and time >= new_t[idx + 1]:
            idx += 1
        next_v = new_v.pop(idx)
        next_t = new_t.pop(idx)
        next_idx = new_idx.pop(idx)
        time -= next_t
        route.append(next_idx)

    
    total_v = 0
    for i in route:
        total_v += v[i]
    print("价值贪婪时:\n需要抢夺的礼物是如下:{},总价值为:{}".format(route, total_v))
        
def time_greedy(n, time):
    '''时间贪婪算法'''
    route = []  #存储需要抢夺的礼物下标
    t_sort = sorted(enumerate(t), key=lambda x: x[1])
    new_idx = [i[0] for i in t_sort]
    new_t = [i[1] for i in t_sort]
    new_v = [v[i] for i in new_idx]
    while time >= new_t[0]:
        idx = 0
        while idx < n - 1 and time >= new_t[idx + 1]:
            idx += 1
        next_v = new_v.pop(idx)
        next_t = new_t.pop(idx)
        next_idx = new_idx.pop(idx)
        time -= next_t
        route.append(next_idx)

    
    total_v = 0
    for i in route:
        total_v += v[i]
    print("时间贪婪时:\n需要抢夺的礼物是如下:{},总价值为:{}".format(route, total_v))

def vt_greedy(n, time):
    '''价时比贪婪算法'''
    route = []  #存储需要抢夺的礼物下标
    vt = [ i/j for i,j in zip(v, t)]
    vt_sort = sorted(enumerate(vt), key=lambda x: x[1])
    new_idx = [i[0] for i in vt_sort]
    new_t = [t[i] for i in new_idx]
    new_v = [v[i] for i in new_idx]
    while time >= new_t[0]:
        idx = 0
        while idx < n - 1 and time >= new_t[idx + 1]:
            idx += 1
        next_v = new_v.pop(idx)
        next_t = new_t.pop(idx)
        next_idx = new_idx.pop(idx)
        time -= next_t
        route.append(next_idx)

    
    total_v = 0
    for i in route:
        total_v += v[i]
    print("价时比贪婪时:\n需要抢夺的礼物是如下:{},总价值为:{}".format(route, total_v))



if __name__ == "__main__":
    #物件总数
    n = int(input("请输入礼物总数:"))
    #物件价值
    v_str = input("请输入每件物品的价值:(逗号隔开) ")
    v_list = v_str.split(",")
    v = list(map(int, v_list))
    # print(v)
    #拿取物品耗时
    t_str = input("请输入拿取每件物品的时间:(逗号隔开) ")
    t_list = t_str.split(",")
    t = list(map(int, t_list))
    #背包的大小
    C = int(input("请输入总时间:"))

    value_greedy(n, C)
    time_greedy(n, C)
    vt_greedy(n,C)

动态规划算法

我仅实现了二维表法
实现如下:

import numpy as np
#0-1背包问题
def zero_one():
    #物件总数
    n = int(input("请输入物件总数:"))
    #物件价值
    v_str = input("请输入每件物品的价值:(逗号隔开) ")
    v_list = v_str.split(",")
    v = [0] + list(map(int, v_list))
    print(v)
    #物件质量
    w_str = input("请输入每件物品的质量:(逗号隔开) ")
    w_list = w_str.split(",")
    w = [0] +list(map(int, w_list))
    print(w)
    #背包的大小
    C = int(input("请输入背包大小:"))
    m = np.zeros([n + 1,C + 1], dtype=np.int)
    for i in range(1, n + 1):
        m[i, 0] = 0
    for W in range(C + 1):
        m[0, W] = 0
    for i in range(1, n + 1):
        for W in range(1, C + 1):
            if w[i] > W:
                m[i, W] = m[i-1, W]
            else:
                m[i, W] = max(m[i-1, W], v[i] + m[i-1, W-w[i]])
    print(m)

if __name__ == "__main__":
    zero_one()

结果比较

我们用同一组数据进行对比:(即开头的文章里面的链接之中用的数据)
转载自https://zhuanlan.zhihu.com/p/30959069
结果如下:
贪婪算法:
在这里插入图片描述
动态规划算法:
在这里插入图片描述
我们可以观察到,贪婪算法的最终结果的最大值为35,而动态规划算法的最大值可以达到40,所以贪婪算法不可以成为01背包问题的最优算法,而动态规划算法是更好的选择。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用模拟退火算法求解01背包问题Python代码: ```python import random import math def simulated_annealing(values, weights, capacity, temperature=1000, cooling_rate=0.95, stopping_temperature=1e-8, num_iterations=1000): """ 使用模拟退火算法求解01背包问题 :param values: 物品价值的列表 :param weights: 物品重量的列表 :param capacity: 背包容量 :param temperature: 初始温度 :param cooling_rate: 降温速率 :param stopping_temperature: 终止温度 :param num_iterations: 每个温度下的迭代次数 :return: 最优解的价值和选择的物品列表 """ num_items = len(values) current_solution = [0] * num_items current_weight = 0 current_value = 0 best_solution = current_solution.copy() best_value = 0 current_temperature = temperature while current_temperature > stopping_temperature: for i in range(num_iterations): # 随机选择一个物品 item_index = random.randint(0, num_items - 1) # 生成新解 new_solution = current_solution.copy() new_solution[item_index] = 1 - new_solution[item_index] new_weight = current_weight + (-1 if current_solution[item_index] else 1) * weights[item_index] new_value = current_value + (-1 if current_solution[item_index] else 1) * values[item_index] # 如果新解不符合约束条件,则不考虑它 if new_weight > capacity: continue # 计算接受概率 delta = new_value - current_value accept_prob = math.exp(delta / current_temperature) # 接受新解 if delta > 0 or random.random() < accept_prob: current_solution = new_solution current_weight = new_weight current_value = new_value # 更新最优解 if current_value > best_value: best_solution = current_solution.copy() best_value = current_value # 降温 current_temperature *= cooling_rate return best_value, [i for i in range(num_items) if best_solution[i] == 1] ``` 使用示例: ```python values = [60, 100, 120] weights = [10, 20, 30] capacity = 50 best_value, best_items = simulated_annealing(values, weights, capacity) print("最优解的价值为:", best_value) print("选择的物品为:", best_items) ``` 输出: ``` 最优解的价值为: 220 选择的物品为: [0, 1] ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值