python 可视化 枚举法01背包问题

Python Version: python 3.6
IDE: Pycharm

使用枚举法解决01背包问题 并用turtle库将其可视化出来
枚举法思想主要还是暴力,将所有可能的组合列出来,再根据重量和总价值进行判断得到最优解,不过一般不推荐此方法,浪费时间。
代码如下:


import turtle
import itertools
import numpy as np


def text(x, y, words, size):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.write(words, font=('微软雅黑', size, 'bold'))


def goods(x, y,color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.begin_fill()
    turtle.fillcolor(color)
    for i in range(4):
        turtle.forward(80)
        turtle.right(90)
    turtle.end_fill()


def bag(x,y):
    turtle.penup()
    turtle.goto(x,y)
    turtle.begin_fill()
    turtle.fillcolor("#FFEBCD")
    turtle.forward(400)
    turtle.right(90)
    turtle.forward(45)
    turtle.right(90)
    turtle.forward(400)
    turtle.right(90)
    turtle.forward(45)
    turtle.right(90)
    turtle.pendown()
    turtle.end_fill()

turtle.speed(3)
m = int(input("get m as the max bag size:"))
n = int(input("get n as the goods tots:"))
bag(-200, 310)
s = "max bag size = "+str(m)
t = "goods tots = "+str(n)
text(-100, 285, s, 10)
text(-100, 270, t, 10)
p = [0]
w = [0]
nn = []
x = -450
y = 240
for i in range(1, n + 1):
    x = 90 + x
    y = y
    weigth = int(input("get weigth:"))
    value = int(input("get val:"))
    w.append(weigth)
    p.append(value)
    nn.append(i)
    n1 = str(i)
    text(x+35, y+3, n1, 10)
    goods(x, y, "LightSkyBlue")
    W = "weigth= " + str(weigth)
    V = "value= " + str(value)
    text(x+10, y-95, W, 10)
    text(x+10, y-110, V, 10)


ss = "total value = "+str(0)+"   total weigth = "+str(0)
text(-300, 70,"best bag: ", 14)
bag(-200, 110)
text(-190, 70, ss, 12)
text(-300, 20,"new bag: ", 14)
bag(-200, 50)

a=[]
for i in range(1, n+1):
    a += list(itertools.combinations(np.array(nn), i))
max = 0
for i in range(0,len(a)):
    countv=0
    countw=0
    x = -450
    y = 240
    for j in a[i]:
        countv += p[j]
        countw += w[j]
        x1 = 90*j + x
        goods(x1, y, "LightPink")
    ss1 = "total value = " + str(countv) + "   total weigth = " + str(countw)
    bag(-200, 50)
    text(-190, 25, ss1, 12)
    if countw <= m:
        if countv > max:
            max = countv
            ss2 = "total value = " + str(max) + "  total weigth = " + str(countw)
            bag(-200, 110)
            text(-190, 75, ss2, 12)
    for k in a[i]:
        x2 = 90*k + x
        y2 = y
        goods(x2, y2, "LightSkyBlue")
turtle.done()

效果如下图(不能发视频我也没有保存成动图所以就随手截了个图):
在这里插入图片描述

发布了125 篇原创文章 · 获赞 56 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Nicht_sehen/article/details/89853912