加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala组合功能不会终止

发布时间:2020-12-16 18:43:13 所属栏目:安全 来源:网络整理
导读:我需要使用流/列表上的 scalas组合方法为30,000个项目列表生成组合 1 to 30000.toStream.combinations(2).size 此功能永远不会完成.当我在python中尝试相同的操作时 r = list(range(1,30000))z = itertools.combinations(r,2)%time sum(1 for _ in z) 操作在
我需要使用流/列表上的 scalas组合方法为30,000个项目列表生成组合

1 to 30000.toStream.combinations(2).size

此功能永远不会完成.当我在python中尝试相同的操作时

r = list(range(1,30000))
z = itertools.combinations(r,2)
%time sum(1 for _ in z)

操作在26.2秒内完成.

这里发生了什么?如何在scala中生成非常大的列表组合?

解决方法

我不知道为什么stdlib中的实现需要这么长时间.但是,这种简单的实现(专门用于配对和列表)与Python的实现相当:

def combinations2[A](l: List[A]): Iterator[(A,A)] =
  l.tails.flatMap(_ match {
    case h :: t => t.iterator.map((h,_))
    case Nil => Iterator.empty
  })

然后

scala> {
     |   val t0 = System.nanoTime
     |   val res = combinations2((1 to 30000).toList).size
     |   val secs = (System.nanoTime - t0) / 1000000.0
     |   s"$res (computed in $secs seconds)"
     | }
res11: String = 449985000 (computed in 24992.487638 seconds)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读