Program to count number of fraction pairs whose sum is 1 in python

PythonServer Side ProgrammingProgramming

Suppose we have a list of fractions where each fraction is individual lists [numerator, denominator] which represents the number (numerator / denominator). We have to find the number of pairs of fractions whose sum is 1.

So, if the input is like fractions = [[2, 7],[3, 12],[4, 14],[5, 7],[3, 4],[1, 4]], then the output will be 4, as (2/7 + 5/7), (3/12 + 3/4), (3/4 + 1/4), (4/14 + 5/7) are the four pairs which sum to 1.

To solve this, we will follow these steps:

  • d := a new map
  • ans := 0
  • for each fraction i in fractions, do
    • x := i[numerator]
    • y := i[denominator]
    • g := gcd of (x, y)
    • x := x / g
    • y := y / g
    • temp_x := y - x
    • temp_y := y
    • if (temp_x, temp_y) is in d, then
      • ans := ans + d[temp_x, temp_y]
    • d[x, y] := 1 + (d[(x, y)] when it is available, otherwise 0)
  • return ans

Let us see the following implementation to get better understanding:

Example Code

Live Demo

class Solution:
   def solve(self, fractions):
   import math

   d = {}
   ans = 0
   for i in fractions:
      x = i[0]
      y = i[1]
      g = math.gcd(x, y)
      x /= g
      y /= g
      temp_x = y - x
      temp_y = y
      if (temp_x, temp_y) in d:
         ans += d[(temp_x, temp_y)]
         d[(x, y)] = d.get((x, y), 0) + 1
      return ans

ob = Solution()
fractions = [[2, 7],[3, 12],[4, 14],[5, 7],[3, 4],[1, 4]]
print(ob.solve(fractions))

Input

[[2, 7],[3, 12],[4, 14],[5, 7],[3, 4],[1, 4]]

Output

4
raja
Published on 25-Nov-2020 12:55:17
Advertisements