In this article we have a given Matrix, test if all rows have similar elements.
Input : test_list = [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Output : True
Explanation : All lists have 2, 3, 4, 6, 7.
Input : test_list = [[6, 4, 2, 7, 3], [7, 5, 6, 4, 2], [2, 4, 7, 3, 6]]
Output : False
Explanation : 2nd list has 5 instead of 3.
In this, we compute the elements' frequency dictionary using Counter(), and compare with each row in Matrix, if they check out then True is returned.
OutputThe original list is : [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Are all rows similar : True
In this, we check for similar elements using sorted(), by ordering all the elements to sorted format.
OutputThe original list is : [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Are all rows similar : True
Time Complexity: O(nlogn) where n is the number of elements in the list “test_list”. The time complexity of the sorted() function is O(n log n)
Auxiliary Space: O(1), no extra space is required
OutputThe original list is : [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Are all rows similar : True
This Python code checks if all the rows in a 2D list have similar frequency of elements. The input is a list of lists test_list, where each inner list represents a row. The code uses a dictionary comprehension to count the frequency of each element in each row, and then compares these dictionaries with the dictionary of the first row to check if they are equal.
OutputThe original list is : [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Are all rows similar : True