Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:typeerror:无序类型_Python - Fatal编程技术网

Python:typeerror:无序类型

Python:typeerror:无序类型,python,Python,我试图在我的3.5 python环境中运行此程序,但它会给我以下错误: “typeerror:无序类型”,第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

我试图在我的3.5 python环境中运行此程序,但它会给我以下错误: “typeerror:无序类型”,第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])
#本机二叉树实现
从heapq导入heapify、heappop、heappush
def打印代码(t,代码长度=“”):
'''
接受“heapq”树的根节点并打印哈夫曼代码。
此函数使用递归生成代码字符串。
'''
如果len(t)<3:
打印(“%s:%s%”(t[1],代码)
其他:
打印代码(t[1],代码\u str+'0')
打印代码(t[2],代码_str+'1')
#初始化输入(数据取自3.20)
树=[
[0.07,'a'],
[0.09,'b'],
[0.12,'c'],
[0.22,'d'],
[0.23,'e']
]
#将输入转换为二叉树
希皮菲(树)
#将树排序为有效的哈夫曼树。
#要执行此操作,请弹出两个节点,然后将它们推回树中的
#具有组合全概率的节点
而len(tree)>1:
x=堆顶(树)
y=堆顶(树)
总概率=x[0]+y[0]
堆堆(树,(总概率,x,y))
#输出
打印代码(树[0])

这是通过比较列表和元组得到的。像这样创建树结构应该可以解决这个问题:

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