Open In App

Python | Test list element similarity

Last Updated : 23 Apr, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a list, your task is to determine the list is K percent same i.e has element that is populated more than K % times. 
Given below are few methods to solve the task.
 

Method #1 Using collections.Counter 

Output:

Initial list [1, 2, 3, 1, 1, 1, 1, 1, 3, 2] 
True


Method #2: Using dictionary and its values 

Output:

initial list [1, 2, 3, 1, 1, 1, 1, 1, 1, 1]
True

Method #3: Using List comprehension and set()


Output
Initial list [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
True


In method #3, we use list comprehension and set() to check if the given list is K percent same i.e has element that is populated more than K % times.

First, the program creates a set of all the unique elements in the list, then using list comprehension, it counts the number of occurrences of each unique element in the original list. The program then checks if the count of any of the unique elements is greater than or equal to (K/100) * len(ini_list1), this check is performed for all the unique elements in the list. If the count of any of the elements is greater than the required value, the program returns True, else it returns False.

Method #4: Using  a for loop: 


Output
Initial list [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
True

Time Complexity: O(N)
Auxiliary Space:  O(N)

Method #5: Using numpy.bincount()

  • Import the numpy module.
  • Pass the list 'lst' to numpy.bincount() to obtain the counts of each element in 'lst'.
  • Get the maximum count from the bincount array.
  • Calculate the threshold value (len(lst) * (k/100)).
  • Check if the maximum count is greater than or equal to the threshold value.
  • Return True if the condition is satisfied, False otherwise.
OUTPUT :
Initial list [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
True

Time Complexity: O(n)
Auxiliary Space: O(max(lst)) (for creating the bincount array)


Practice Tags :

Similar Reads