CSP-J,GESP备必神器哈!!!! 在教学上大有用处。根据权值构建哈夫曼树并且画出哈夫曼树Python海龟编程代码

CSP-J,GESP备必神器哈!!!! 在教学上大有用处。根据权值构建哈夫曼树并且画出哈夫曼树Python海龟编程代码

# CSP-J,GESP备必神器哈!!!!  在教学上大有用处。根据权值构建哈夫曼树并且画出哈夫曼树Python海龟编程代码:
class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def build_tree(weights):                     # 构建哈夫曼树
    nodes = [Node(w) for w in weights]
    while len(nodes) > 1:
        nodes.sort(key=lambda x: x.value)
        left = nodes.pop(0)
        right = nodes.pop(0)
        parent = Node(left.value + right.value, left, right)
        nodes.append(parent)
    return nodes[0]

def make_codes(node, code='', codes={}):         # 构建哈夫曼编码
    if node.left is None and node.right is None: # 是叶子结点了
        codes[node.value] = code
    else:
        make_codes(node.left, code + '0', codes)
        make_codes(node.right, code + '1', codes)
    return codes

# 权值测试表
weights = [3, 4, 6, 8, 12, 13, 15, 18, 25, 40]
weights = [19,21,2,3,6,7,10,32]
weights = [14,6,7,33,12,28]
weights = [19,21,2,3,6,7,10,32]
weights = [4,2,7,11,8,9]

root = build_tree(weights)
huffman_codes = make_codes(root)
print(huffman_codes)

import turtle
def fd2(distance):   
    turtle.penup();turtle.fd(distance*0.2);turtle.pendown()
    turtle.fd(distance*0.6);turtle.penup();turtle.stamp();turtle.fd(distance*0.2)

def draw_dot(num):  # 在坐标点打点,并在点上写上数字
    dx = 0
    dy = -8
    ft = ('宋体',10,'normal')
    pos = turtle.position()
    turtle.dot(30,'blue')   # 直径为30,蓝色的圆点
    x = pos[0] + dx         # dx和dy用于临时调整海龟坐标偏移量
    y = pos[1] + dy
    turtle.goto(x,y)
    turtle.color('white')  # 写白色字
    turtle.write(num,align='center',font=ft)
    turtle.color('black')
    turtle.goto(pos)
    
def draw_binary_tree(tree,dis,angle): # 画二叉树,请把它进行美化
    draw_dot(tree.value)    
    if tree.left!=None:
        turtle.right(angle);fd2(dis);turtle.left(angle)
        draw_binary_tree(tree.left,dis*0.75,angle);turtle.right(angle)
        turtle.bk(dis);turtle.left(angle)
    if tree.right!=None:
        turtle.left(angle);fd2(dis);turtle.right(angle)
        draw_binary_tree(tree.right,dis*0.75,angle);turtle.left(angle)
        turtle.bk(dis);turtle.right(angle)
turtle.delay(0)
turtle.speed(0)
turtle.right(90)
turtle.penup()
turtle.bk(180)
draw_binary_tree(root,140,50)
turtle.penup()
turtle.ht()


李兴球

李兴球的博客是Python创意编程原创博客