【问题标题】:R equivalent of Python's heapq.heapify()?R 相当于 Python 的 heapq.heapify()?
【发布时间】:2016-03-19 17:39:15
【问题描述】:

标题中已经说明了一切。我正在寻找与 Python 的heapq.heapify() 等效的 R。我找不到它,但我希望它存在于某个地方。

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

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

【问题讨论】:

  • 快速谷歌搜索出现inside-r.org/packages/cran/Containers,但我没有资格评论它的用处。
  • @tripleee 谢谢。 Containers 包显然已从 CRAN 中删除,但我会尝试下载存档并查看堆函数的源代码是否是用 R 编写的,以便我可以在我的 Shiny 应用程序中获取它
  • 除非来自 r 的人过来说它可以从标准包中获得,那么这是对资源和/或工具的请求,这是题外话
  • @Drew 我的问题与here 的其他几十个问题有何不同?
  • 您的结果中的许多问题都询问了一个核心概念,例如如何在分隔符上拆分字符串,或者当您知道相应的 Python 概念时使用什么数据类型。可以说,图书馆的其余任务也应该关闭。见meta.stackoverflow.com/questions/251134/… ...我还尝试搜索“为什么我的关闭了,而这些其他人甚至都不是他们也很糟糕”,但无法很快找到;但答案应该是显而易见的。

标签: python r heap code-translation


【解决方案1】:

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

只需将未排序的向量传递给函数,并指定是要实现min-heapify 还是max-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 中:

heapify(c(30,1,1,0,3,3,3,2,14,25,3,10,4,3),min=TRUE)$heap
[1]  0  1  1  2  3  3  3 30 14 25  3 10  4  3

在 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]

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 2014-10-31
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2019-07-14
    • 2012-05-27
    相关资源
    最近更新 更多