简体   繁体   English

Python 中是否有 function 用于在具有约束的数据结构中插入元素

[英]Is there a function in Python to insert an element in a data structure with constraints

I have a data structure with a sorted array with k elements and a Minimum Heap with n - k elements.我有一个数据结构,其中包含一个带有 k 个元素的排序数组和一个带有 n - k 个元素的最小堆。

I've already coded the Minimum Heap and a helper function to insert the element into the array.我已经编写了最小堆和一个助手 function 来将元素插入到数组中。

Now I would like to code the part to insert an element either into the heap or use the helper function.现在我想对该部分进行编码以将元素插入堆中或使用帮助程序 function。

constraints for insertion of the new element as follows:插入新元素的约束如下:

  1. case:案子:
  • <[−1]: insert into the sorted array -> use the helper function <[−1]: 插入已排序的数组 -> 使用助手 function
  • Insert ′ into the heap using heap insert.使用堆插入将'插入堆中。
  1. case:案子:
  • ≥[−1]: insert into the heap. ≥[−1]:插入到堆中。
# helper function
    def insert_array(self, elt):
        self.A.append(elt)
        j = len(self.A)-1
        while (j >= 1 and self.A[j] < self.A[j-1]):
            (self.A[j], self.A[j-1]) = (self.A[j-1], self.A[j])
            j = j -1 
        return


    def insert(self, elt):
        size = self.size()
        if size <= self.k:
            self.insert_array(elt)
            return 
        elif elt < self.A[ - 1 ]:
            self.insert_array(elt)
        else:   
            self.H.append(elt)
            self.bubble_up(len(self.H) - 1)

While I am not sure I fully understand your question, you can do the following:虽然我不确定我是否完全理解您的问题,但您可以执行以下操作:

if j < A[k-1]:
    insert j into sorted array using helper function
else:
    insert j into heap using heap insert

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM