- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

- Related Questions & Answers
- Program to count number of paths whose sum is k in python
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
- Program to count number of consecutive lists whose sum is n in C++
- Number of pairs whose sum is a power of 2 in C++
- Count number of distinct pairs whose sum exists in the given array in C++
- Program to count maximum number of distinct pairs whose differences are larger than target in Python
- Count pairs in array whose sum is divisible by 4 in C++
- Count pairs in array whose sum is divisible by K in C++
- Count of pairs in an array whose sum is a perfect square in C++
- Program to find number of sublists whose sum is given target in python
- Program to count number of permutations where sum of adjacent pairs are perfect square in Python
- Program to count number of valid pairs from a list of numbers, where pair sum is odd in Python
- Count all pairs of adjacent nodes whose XOR is an odd number in C++
- Program to find max number of K-sum pairs in Python
- Program to count indices pairs for which elements sum is power of 2 in Python

Advertisements