gpt4 book ai didi

Python:类型错误:不可排序的类型

转载 作者:太空宇宙 更新时间:2023-11-04 05:12:33 25 4
gpt4 key购买 nike

我试图在我的 3.5 python 环境中运行这个程序,但它会给我这个错误:“类型错误:不可排序的类型”,第 33 行:

heappush(tree, (total_prob, x, y))

这是程序

# Native binary tree implementation
from heapq import heapify, heappop, heappush

def printCodes(t, code_str = ''):
'''
Accept the root node of a 'heapq' tree and print the Huffman codes.
This function uses recursion to build the codes strings.
'''
if len(t) < 3:
print('%s: %s' % (t[1], code_str))
else:
printCodes(t[1], code_str + '0')
printCodes(t[2], code_str + '1')

# Initialize the input (data taken from 3.20)
tree = [
[0.07, 'a'],
[0.09, 'b'],
[0.12, 'c'],
[0.22, 'd'],
[0.23, 'e']
]

# Convert the input into a binary tree
heapify(tree)

# Sort the tree into a valid Huffman tree.
# To do this, pop two nodes, then push them back into the tree under a
# node with the combined total probability
while len(tree) > 1:
x = heappop(tree)
y = heappop(tree)
total_prob = x[0] + y[0]
heappush(tree, (total_prob, x, y))

# Output
printCodes(tree[0])

最佳答案

这是将列表与元组进行比较。改为像这样创建树结构应该可以解决它:

tree = [
(0.07, 'a'),
(0.09, 'b'),
(0.12, 'c'),
(0.22, 'd'),
(0.23, 'e'),
]

关于Python:类型错误:不可排序的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com