'How to change the code from Scala to Python

def computeTotalVariationDistance(p: Distribution, q: Distribution): Double = {
    val pSum = p.sum
    val qSum = q.sum
    val l1Distance = p.zip(q)
      .map { case (_, pVal, qVal) =>
        math.abs((pVal / pSum) - (qVal / qSum))
      }
      .sum

    0.5 * l1Distance
  }

Can someone help me to change this code into python.



Solution 1:[1]

It's actually relatively straightforward. Instead of map, you can use list comprehension:

l1Distance = sum(
             [abs((pVal / pSum) - (qVal / qSum)) 
              for pVal, qVal in zip(p, q)]
             )

I have not tested this but it should work, or something very similar.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kutschkem