Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to count number of fraction pairs whose sum is 1 in python
Suppose we have a list of fractions where each fraction is represented as [numerator, denominator]. We need to find the number of pairs of fractions whose sum equals 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.
Algorithm
To solve this, we follow these steps ?
- Create a dictionary to store fraction frequencies in reduced form
- For each fraction, reduce it to lowest terms using GCD
- Calculate the complement fraction needed to sum to 1
- Check if the complement exists in our dictionary
- Add current fraction to dictionary for future lookups
Implementation
import math
def count_fraction_pairs(fractions):
d = {}
ans = 0
for fraction in fractions:
x = fraction[0] # numerator
y = fraction[1] # denominator
# Reduce fraction to lowest terms
g = math.gcd(x, y)
x //= g
y //= g
# Calculate complement fraction (what we need to sum to 1)
# If current fraction is x/y, complement is (y-x)/y
temp_x = y - x
temp_y = y
# Check if complement exists in dictionary
if (temp_x, temp_y) in d:
ans += d[(temp_x, temp_y)]
# Add current fraction to dictionary
d[(x, y)] = d.get((x, y), 0) + 1
return ans
# Test with example
fractions = [[2, 7], [3, 12], [4, 14], [5, 7], [3, 4], [1, 4]]
result = count_fraction_pairs(fractions)
print(f"Number of pairs that sum to 1: {result}")
Number of pairs that sum to 1: 4
How It Works
Let's trace through the algorithm with an example ?
import math
def count_fraction_pairs_with_trace(fractions):
d = {}
ans = 0
print("Processing fractions:")
for i, fraction in enumerate(fractions):
x = fraction[0]
y = fraction[1]
print(f"\nStep {i+1}: Processing {x}/{y}")
# Reduce to lowest terms
g = math.gcd(x, y)
x //= g
y //= g
print(f" Reduced form: {x}/{y}")
# Calculate complement
temp_x = y - x
temp_y = y
print(f" Complement needed: {temp_x}/{temp_y}")
# Check for existing complement
if (temp_x, temp_y) in d:
pairs_found = d[(temp_x, temp_y)]
ans += pairs_found
print(f" Found {pairs_found} complement(s)! Total pairs: {ans}")
else:
print(f" No complement found yet")
# Add current fraction
d[(x, y)] = d.get((x, y), 0) + 1
print(f" Dictionary: {d}")
return ans
# Test with smaller example
fractions = [[2, 7], [5, 7], [3, 4], [1, 4]]
result = count_fraction_pairs_with_trace(fractions)
print(f"\nFinal result: {result}")
Processing fractions:
Step 1: Processing 2/7
Reduced form: 2/7
Complement needed: 5/7
No complement found yet
Dictionary: {(2, 7): 1}
Step 2: Processing 5/7
Reduced form: 5/7
Complement needed: 2/7
Found 1 complement(s)! Total pairs: 1
Dictionary: {(2, 7): 1, (5, 7): 1}
Step 3: Processing 3/4
Reduced form: 3/4
Complement needed: 1/4
No complement found yet
Dictionary: {(2, 7): 1, (5, 7): 1, (3, 4): 1}
Step 4: Processing 1/4
Reduced form: 1/4
Complement needed: 3/4
Found 1 complement(s)! Total pairs: 2
Dictionary: {(2, 7): 1, (5, 7): 1, (3, 4): 1, (1, 4): 1}
Final result: 2
Key Points
- GCD Reduction: Fractions are reduced to prevent counting equivalent fractions as different
- Complement Calculation: For fraction x/y, complement is (y-x)/y to sum to 1
- Hash Map Lookup: Efficient O(1) lookup to find existing complements
- Order Independence: Algorithm works regardless of input order
Time and Space Complexity
- Time Complexity: O(n × log(min(a,b))) where n is number of fractions and log factor comes from GCD calculation
- Space Complexity: O(n) for the dictionary to store unique fractions
Conclusion
This algorithm efficiently counts fraction pairs that sum to 1 by using GCD reduction and complement lookup. The key insight is storing reduced fractions in a hash map and checking for their complements as we process each fraction.
Advertisements
