用于查找矩阵每一行的冗余率的Python程序
给定一个矩阵,任务是编写一个Python程序,可以计算每行的冗余率,即重复字符总数的比率。
冗余率:元素的重复率。
公式:
1 - (total unique elements) / (total elements)
例子:
Input : test_list = [[4, 5, 2, 4, 3], [5, 5, 5, 5, 5], [8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
Output : [0.19999999999999996, 0.8, 0.6, 0.0]
Explanation : 1 – [2/5] = 0.6 for 3rd row.
Input : test_list = [[5, 5, 5, 5, 5], [8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
Output : [0.8, 0.6, 0.0]
Explanation : 1 – [2/5] = 0.6 for 2nd row.
方法 1:使用循环和set()
在这里,我们使用使用集合长度计算的唯一元素的分数来执行计算速率的任务,列表中的所有元素从 1 中减去。
例子:
Python3
# initializing list
test_list = [[4, 5, 2, 4, 3], [5, 5, 5, 5, 5],
[8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# getting Redundancy
res.append(1 - len(set(sub)) / len(sub))
# printing result
print("Matrix Redundancy ? : " + str(res))
Python3
# initializing list
test_list = [[4, 5, 2, 4, 3], [5, 5, 5, 5, 5],
[8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension for one liner
res = [1 - len(set(sub)) / len(sub) for sub in test_list]
# printing result
print("Matrix Redundancy ? : " + str(res))
输出:
The original list is : [[4, 5, 2, 4, 3], [5, 5, 5, 5, 5], [8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
Matrix Redundancy ? : [0.19999999999999996, 0.8, 0.6, 0.0]
方法 2:使用列表理解
使用与上述方法类似的功能,唯一的区别是它的一个线性解决方案是使用列表理解计算的。
例子:
蟒蛇3
# initializing list
test_list = [[4, 5, 2, 4, 3], [5, 5, 5, 5, 5],
[8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension for one liner
res = [1 - len(set(sub)) / len(sub) for sub in test_list]
# printing result
print("Matrix Redundancy ? : " + str(res))
输出:
The original list is : [[4, 5, 2, 4, 3], [5, 5, 5, 5, 5], [8, 7, 8, 8, 7], [1, 2, 3, 4, 5]]
Matrix Redundancy ? : [0.19999999999999996, 0.8, 0.6, 0.0]