我正在将一段代码从Python转换为R,以在总和重复时定位一系列数字的位置。对我来说,翻译是一对一的,但是与R代码相比,执行python代码只需不到一秒钟,而R代码则需要一个小时左右。我想知道我是否会错过两种语言的数据结构中的任何内容。为什么执行代码会有如此大的时差?当我在R中编写以下Python代码时,有什么更好或更有效的选择?

蟒蛇:

def calculate(data):
    found = set([0])
    total = 0
    while True:
        for num in data:
            total = total + num
            if total in found:
                return total
            else:
                found.add(total)


R:

calculate <- function(input) {
  found = set(0)
  total = 0
  while (TRUE) {
   for (num in input) {
     total = total + num
     if (total %in% found) {
         return(total)
     } else {
         found <- c(found, total)
     }
    }
  }
}

最佳答案

猜想这是大多数事物在R中不可变的组合(因此向量级联每次都会分配新对象)和R的%in%运算符为O(N),而in则为O(1)蟒蛇

09-11 00:07
查看更多