【问题标题】:how to check if a list[string] is subset of another list[string] in scala如何检查列表[字符串]是否是scala中另一个列表[字符串]的子集
【发布时间】:2017-04-27 23:27:03
【问题描述】:

我基本上有两个文件 input1 和 input2(都是 List[string])。我想检查它们是否是彼此/相同的子字符串。所以,我有以下

Val conf = new SparkConf().setAppName (“check identical”)
Val sc = new SparkContext(conf)
val input 1 = sc.textFile(inputFile-L)
Val input 2 = sc.textFile(inputFile-M) 

// split up words
val words1 = input1.flatMap(line=> line.split(""))
Val words2 = input2.flatMap(line=>line.split(""))

// Transform into word and count 
val counts1 = words1.map(word => (word, reducebyKey{case(x,y) => x+y})
val counts2 = words2.map(word => (word, reducebyKey{case(x,y) => x+y})

通过上面,我确定字数是一样的,现在如何比较子集?有什么简单的方法可以采取吗?

【问题讨论】:

  • 能否添加数据样本和预期结果?不确定在这种情况下“子集”/“子字符串”是什么意思
  • 如果 (a diff b).isEmpty 则 a 是 b 的子集
  • @LuigiPlinge 确定。但是看看这里如何使用子集和子串,就好像它们可以互换一样。子字符串需要排序。
  • 我不认为示例代码能像你说的那样做。

标签: scala word-count


【解决方案1】:

这应该可以解决问题:

val notInWords1 = words2.filterNot(w => words1.contains(w))
val notInWords2 = words1.filterNot(w => words2.contains(w))

val bothAreEqual = notInWords1.isEmpty && notInWords2.isEmpty

val subset = Option( if(notInWords1.isEmpty && notInWords2.nonEmpty) words2
                else if(notInWords2.isEmpty && notInWords1.nonEmpty) words1)

val oneIsASubsetOfTheOther = subset.isDefined
val words1IsSubsetOfWords2 = subset.getOrElse(false) == words1
val words2IsSubsetOfWords1 = subset.getOrElse(false) == words2

【讨论】:

  • 没有区别,我基本上是在尝试编写一个函数来检查 M 是否是 L 的子集@Mr D
  • @pruthvi 我添加了一堆东西,应该能满足你所​​需要的我相信
  • oneIsASubsetOfTheOther 是做什么用的?
  • 要检查其中一个是否是另一个的子集(两者可能相等或它们可能不同但不是子集),我并没有在代码中真正使用它,但我认为它' d 是一个很好的补充......我也可以根据 oneIsASubsetOfTheOther 实现 words1IsSubsetOfWords2 但结果会是一样的,我认为没有理由强迫它依赖它
  • 谢谢!这有帮助。基本上我不知道“子集”之类的功能已经存在!
【解决方案2】:

这个怎么样?

words1.foreach(words2.contains)

【讨论】:

    【解决方案3】:

    使用 Scala 编程:

    def hasSequence[A](l1: List[A], l2: List[A]): Boolean =  {
        def matchSeq(l1: List[A], l2: List[A], l2Original: List[A]): Boolean = {
            (l1, l2) match {
               case (_, Nil) => true
               case (Nil, _) => false //short circuit this case if l2.size > l1.size
               case (h1::t1, h2::t2) if h1 == h2 => matchSeq(t1, t2, l2Original)
               case (_::tail1, _) =>matchSeq(tail1, l2Original, l2Original)
            }
         }
      if(l2.isEmpty) false else matchSeq(l1, l2, l2)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-06
      • 2012-11-23
      • 2022-07-01
      • 1970-01-01
      • 2011-06-18
      • 2013-04-29
      • 2020-10-14
      相关资源
      最近更新 更多