R相当于Python的健康()?

2024-04-18 05:40:52 发布

您现在位置:Python中文网/ 问答频道 /正文

标题里说的都是。我在寻找Python的^{}的R等价物。我找不到它,但我希望它存在于某处。在

heapq是一个堆队列实现模块,其成员函数heapify接受一个对象列表作为输入,并返回一个堆对象对象,其中包含对这些对象的引用作为堆的成员。在

编辑:我不能在R中使用rPython调用Python代码,因为最终的脚本将是一个闪亮的应用程序的一部分(它几乎不能与rPython一起工作,而且无论如何也不允许导入模块)。在


Tags: 模块对象函数代码脚本应用程序编辑标题
1条回答
网友
1楼 · 发布于 2024-04-18 05:40:52

我通过移植找到的Matlab代码here创建了这个heapifyR函数(这比从Python移植要容易,因为与R一样,Matlab使用1索引基线)。在

只需向函数传递一个未排序的向量,并指定要实现min-heapify还是{}。我将Python的heapq.heapify()(默认情况下是min-heapify)进行比较,结果是一样的。在

heapify = function(input_vector, min){

  # below is the maxheapify algorithm
  # minheapify = maxheapify with sign change at the beginning and at the end

  if (min==TRUE){input_vector = - input_vector}

    count = length(input_vector)

    start = floor(count/2)

    while (start >= 1){
      root = start
      theEnd = count

      while ((root * 2) <= theEnd){

        child = root * 2

        if ((child + 1 <= theEnd) & (input_vector[child] < input_vector[child+1])){
          child = child + 1
        }

        if (input_vector[root] < input_vector[child]){

          temp = input_vector[root]
          input_vector[root] = input_vector[child]
          input_vector[child] = temp

          root = child

        } else {
          break
        }

      }

        start = start - 1
    }

    if (min==TRUE){input_vector = - input_vector}

output = list(heap=input_vector)
}

示例:

在R中:

^{pr2}$

在Python中:

test = [30,1,1,0,3,3,3,2,14,25,3,10,4,3]
heapq.heapify(test)
test
Out: [0, 1, 1, 2, 3, 3, 3, 30, 14, 25, 3, 10, 4, 3]

相关问题 更多 >