Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.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中调用heapify_up函数?_Python_Algorithm_Heap - Fatal编程技术网

如何在Python中调用heapify_up函数?

如何在Python中调用heapify_up函数?,python,algorithm,heap,Python,Algorithm,Heap,我试图调用一个给定的函数“heapify_up”,它将一个值滴入堆中。它将堆的索引i处的值与其父级进行比较,如果违反了heap属性,则交换这两个值 我不断地犯错误: File "try.py", line 30, in heapify_up while (getattr(self.heap[parent], self.sorting_key) < IndexError: list index out of range 文件“try.py”,第30行,在heapify\u up中

我试图调用一个给定的函数“heapify_up”,它将一个值滴入堆中。它将堆的索引i处的值与其父级进行比较,如果违反了heap属性,则交换这两个值

我不断地犯错误:

File "try.py", line 30, in heapify_up
    while (getattr(self.heap[parent], self.sorting_key) <
IndexError: list index out of range
文件“try.py”,第30行,在heapify\u up中
while(getattr(self.heap[parent],self.sorting\u键)<
索引器:列表索引超出范围
下面是我的代码

class Heap:
    def __init__(self, sorting_key):
        """Initializes a new instance of a heap.

        Args:
            sorting_key: Specifies the attribute of the object inserted
            into the heap, on the basis of which the heap was created.
        """
        self.heap = list()
        self.mapping = dict()
        self.sorting_key = sorting_key

    def heapify_up(self, child):
        """Standard heapify operation, as described in CLRS.
        Works by swapping the element originially at index child in the heap
        with its parent until the heap property is satisfied. Modifies the
        appropriate heap attribute

        Args:
            child: Index of the element that violates the heap property

        Returns:
            None
        """
        parent = (child - 1) / 2
        # Swaps the element originally at the index child with its parent
        # until the value of the specifed attribute of the parent is greater
        # than the value of the specified attribute of the element itself
        while (getattr(self.heap[parent], self.sorting_key) <
               getattr(self.heap[child], self.sorting_key)):
            if (parent == -1):
                # This means child was 0, which means we have reached the
                # top of the heap
                return

            # Swap the mappings as well to ensure that future references in
            # the mapping dict refer to the correct position of the object in
            # the heap
            self.mapping[self.heap[parent].player] = child
            self.mapping[self.heap[child].player] = parent

            # Swap the parent and the child
            temp = self.heap[parent]
            self.heap[parent] = self.heap[child]
            self.heap[child] = temp

            # Move the child and parent pointers up the heap
            child = parent
            parent = (child - 1) / 2

x=Heap([16,4,10,14,7,9,3,2,8,1])  # sample list
x.heapify_up(4)  # index of child that violates the heap property
print x.sorting_key
类堆:
def uuu init uuuu(自,排序键):
“”“初始化堆的新实例。
Args:
排序键:指定插入对象的属性
进入堆中,并在此基础上创建堆。
"""
self.heap=list()
self.mapping=dict()
self.sorting\u key=排序\u key
def heapify_up(自我、孩子):
“”“标准heapify操作,如CLRS中所述。
其工作原理是在堆中的索引子级原始交换元素
直到满足heap属性为止。修改
适当的堆属性
Args:
子级:违反heap属性的元素的索引
返回:
没有一个
"""
父项=(子项-1)/2
#将最初位于索引子级的元素与其父级交换
#直到父级的指定属性的值更大
#而不是元素本身的指定属性的值
while(getattr(self.heap[parent],self.sorting\u键)<
getattr(self.heap[child],self.sorting_key)):
如果(父项==-1):
#这意味着child为0,这意味着我们已到达
#最重要的
返回
#交换映射,以确保将来的引用
#映射dict指的是对象在中的正确位置
#堆
self.mapping[self.heap[parent].player]=child
self.mapping[self.heap[child].player]=父
#交换父对象和子对象
temp=self.heap[parent]
self.heap[parent]=self.heap[child]
self.heap[child]=temp
#将子指针和父指针向上移动到堆中
子=父
父项=(子项-1)/2
x=堆([16,4,10,14,7,9,3,2,8,1])#样本列表
x、 heapify_up(4)#违反heap属性的子级索引
打印x.U键

您将
self.heap
留下一个空列表。任何索引将抛出一个
索引器
异常:

class Heap:
    def __init__(self, sorting_key):
        # ...
        self.heap = list()
您的列表改为分配给
排序\u键
,这与
排序\u键
的文档使用不匹配:

排序键:指定插入对象的属性 进入堆中,并在此基础上创建堆。 您的代码假定一个具有属性的对象列表,在
排序键
属性中命名。但是您的代码随后传入一个整数列表,而没有排序键。
heapify\u up
函数似乎也期望堆元素具有
.player
属性,而这些整数都没有。这段代码永远不会使用您提供的输入

在使用
Heap\u up
方法之前,您需要确定
堆需要跟踪和修复的状态


请注意,Python标准库已经提供了一个;文档链接到源代码,它是通用的,并且没有像此代码看起来那样绑定到特定的堆元素类型。

很抱歉,我没有得到它。我在调用函数时没有使用self.heap。我为x.sorting\u键分配了一个列表。这对调用x.hepify\u有何影响?@user3810193:您的
self.heap
属性是一个空列表,但您正试图使用
self.heap[child]
self.heap[parent]对其进行索引
。空列表中没有元素,因此您无法索引到其中。您通常从现有列表初始化堆。您的
排序键
属性用作
getattr()中堆元素的属性
调用,属性永远不能是列表,所以这里真的有点混乱。你完全明白在这段代码中
self.heap
self.sorting\u key
要做什么吗?谢谢Martijin。我不太知道如何使用现有列表初始化堆(将其分配给self.heap)。你能举个例子吗?我试过x=Heap(),x.Heap([list]),这似乎也错了。@user3810193:
x=Heap(attribute\u name)
然后
x.Heap=[element1,element2,…]
。但是你的堆需要包含具有给出排序值的属性的对象。对不起,你能解释一下这是什么意思吗“包含具有给定排序值的属性的对象”?基本上,我想知道如何使用该类创建列表(例如[16,4,10,14,7,9,3,2,8,1]),并通过将索引[2]与索引[5]交换来对其进行重分类。