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 the redundancy rates for each row of a matrix
When it is required to find the redundancy rates for every row of a matrix, a simple iteration and the append method can be used. The redundancy rate represents how many duplicate values exist in each row, calculated as 1 - (unique_elements / total_elements).
Understanding Redundancy Rate
The redundancy rate formula is ?
redundancy_rate = 1 - (number_of_unique_elements / total_elements)
A redundancy rate of 0 means all elements are unique, while 1 means all elements are identical.
Example
Below is a demonstration of finding redundancy rates for each row ?
my_matrix = [[91, 52, 12, 29, 33], [54, 54, 54, 54, 54], [11, 22, 33, 59, 95]]
print("The matrix is :")
print(my_matrix)
redundancy_rates = []
for row in my_matrix:
redundancy_rates.append(1 - len(set(row)) / len(row))
print("The redundancy rates are :")
print(redundancy_rates)
The output of the above code is ?
The matrix is : [[91, 52, 12, 29, 33], [54, 54, 54, 54, 54], [11, 22, 33, 59, 95]] The redundancy rates are : [0.0, 0.8, 0.0]
How It Works
The algorithm works as follows ?
- Row 1: [91, 52, 12, 29, 33] has 5 unique elements out of 5 total ? redundancy = 1 - 5/5 = 0.0
- Row 2: [54, 54, 54, 54, 54] has 1 unique element out of 5 total ? redundancy = 1 - 1/5 = 0.8
- Row 3: [11, 22, 33, 59, 95] has 5 unique elements out of 5 total ? redundancy = 1 - 5/5 = 0.0
Alternative Approach Using List Comprehension
You can achieve the same result more concisely ?
my_matrix = [[91, 52, 12, 29, 33], [54, 54, 54, 54, 54], [11, 22, 33, 59, 95]]
redundancy_rates = [1 - len(set(row)) / len(row) for row in my_matrix]
print("The redundancy rates are :")
print(redundancy_rates)
The redundancy rates are : [0.0, 0.8, 0.0]
Conclusion
The redundancy rate formula 1 - len(set(row)) / len(row) efficiently calculates duplicate ratios in matrix rows. Use list comprehension for concise code or explicit loops for better readability.
