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
Python Program to find out the number of matches in an array containing pairs of (base, number)
We need to find pairs in the format (base, number) that represent the same decimal value. For example, (10, 15) means 15 in base 10, and (8, 17) means 17 in base 8. Both equal 15 in decimal, so they match.
So, if the input is like num_inputs = 2, input_arr = [(10, 15), (8, 17)], then the output will be 1.
The variable num_inputs specifies the number of inputs, and the array input_arr lists the number pairs. Here if we look at the two pairs: 15 in base 10 (decimal) is the same as 17 in base 8 (octal). Both equal 15 in decimal, so there is one match.
Algorithm Steps
To solve this, we will follow these steps ?
Create a dictionary to count occurrences of each decimal value
For each pair (base, number), convert the number from given base to decimal
Count how many times each decimal value appears
For each decimal value appearing n times, the number of matches is n*(n-1)/2
Example
Let us see the following implementation to get better understanding ?
from collections import defaultdict
def solve(num_inputs, input_arr):
temp_dict = defaultdict(int)
for i in range(num_inputs):
base, number = input_arr[i][0], input_arr[i][1]
# Convert number from given base to decimal
decimal_value = int(str(number), base)
temp_dict[decimal_value] += 1
cnt = 0
for value in temp_dict.values():
# Calculate combinations: n*(n-1)/2
cnt += value * (value - 1) // 2
return cnt
# Test the function
print(solve(2, [(10, 15), (8, 17)]))
The output of the above code is ?
1
How It Works
The algorithm converts each (base, number) pair to its decimal equivalent:
(10, 15) ? 15 in decimal
(8, 17) ? 1×8¹ + 7×8? = 8 + 7 = 15 in decimal
Both pairs represent the same decimal value (15), so we have 2 occurrences. The number of matches for n occurrences is n×(n-1)/2 = 2×1/2 = 1.
Another Example
from collections import defaultdict
def solve(num_inputs, input_arr):
temp_dict = defaultdict(int)
for i in range(num_inputs):
base, number = input_arr[i][0], input_arr[i][1]
decimal_value = int(str(number), base)
temp_dict[decimal_value] += 1
cnt = 0
for value in temp_dict.values():
cnt += value * (value - 1) // 2
return cnt
# Test with multiple matches
print(solve(4, [(10, 15), (8, 17), (16, 15), (2, 1111)]))
The output of the above code is ?
6
Here we have:
(10, 15) ? 15 decimal
(8, 17) ? 15 decimal
(16, 15) ? 21 decimal
(2, 1111) ? 15 decimal
Three pairs equal 15 in decimal, giving us 3×2/2 = 3 matches for value 15. One pair equals 21, giving 0 matches. Total = 3 matches.
Conclusion
This solution efficiently finds matching number pairs by converting all values to decimal and counting combinations. The time complexity is O(n) where n is the number of input pairs.
---