Python | Test list element similarity
Last Updated :
23 Apr, 2023
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
Python3
# Python3 code to demonstrate
# to check whether the list
# K percent same or not
from collections import Counter
# initializing list
ini_list1 = [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
# printing initial list
print ("Initial list", ini_list1)
# initializing K
K = 60
# code to check whether list is K % same or not
i, freq = Counter(ini_list1).most_common(1)[0]
if len(ini_list1)*(K / 100) <= freq:
print("True")
else:
print("False")
Output:
Initial list [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
True
Method #2: Using dictionary and its values
Python3
# Python3 code to demonstrate
# to check whether the list
# K percent same or not
from collections import Counter, defaultdict
# initializing list
ini_list1 = [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
# printing initial list
print ("Initial list", ini_list1)
# initializing K
K = 60
# code to check whether list is K % same or not
freq = defaultdict(int)
for x in ini_list1:
freq[x] += 1
freq = freq.values()
if max(freq) >= (K / 100) * sum(freq):
print ("True")
else:
print ("False")
Output:
initial list [1, 2, 3, 1, 1, 1, 1, 1, 1, 1]
True
Method #3: Using List comprehension and set()
Python3
# Python3 code to demonstrate
# to check whether the list
# K percent same or not
# initializing list
ini_list1 = [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
# printing initial list
print ("Initial list", ini_list1)
# initializing K
K = 60
# code to check whether list is K % same or not
count = len([x for x in set(ini_list1) if ini_list1.count(x) >= (K/100) * len(ini_list1)])
if count > 0:
print("True")
else:
print("False")
#This code is contributed by Edula Vinay Kumar Reddy
OutputInitial 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:
Python3
def is_k_percent_same(lst, k):
count = {}
for num in lst:
if num in count:
count[num] += 1
else:
count[num] = 1
most_common = max(count.values())
if most_common >= len(lst) * (k/100):
return True
else:
return False
ini_list1 = [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
# printing initial list
print ("Initial list", ini_list1)
K = 60
print(is_k_percent_same(ini_list1, K))
#This code is contributed by Jyothi pinjala.
OutputInitial 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.
Python3
import numpy as np
def is_k_percent_same(lst, k):
bincount = np.bincount(lst)
most_common = np.max(bincount)
threshold = len(lst) * (k/100)
if most_common >= threshold:
return True
else:
return False
ini_list1 = [1, 2, 3, 1, 1, 1, 1, 1, 3, 2]
# printing initial list
print ("Initial list", ini_list1)
K = 60
print(is_k_percent_same(ini_list1, K))
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)
Similar Reads
Python - Alternate elements Similarity
Given list of elements, check if all the alternate elements are equal to K. Input : test_list = [5, 3, 5, 2, 5, 8, 9], K = 5 Output : False Explanation : 9 != 5, hence False. Input : test_list = [4, 3, 4, 2, 4], K = 4 Output : True Explanation : All alternates equal to 4. Method #1 : Using loop This
4 min read
Similarity Metrics of Strings - Python
In Python, we often need to measure the similarity between two strings. For example, consider the strings "geeks" and "geeky" âwe might want to know how closely they match, whether for tasks like comparing user inputs or finding duplicate entries. Let's explore different methods to compute string si
3 min read
Python - Elements with K lists similar index value
Sometimes, while working with data, we can have a problem in which we need to get elements which are similar in K lists in particular index. This can have application in many domains such as day-day and other domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using z
5 min read
Python - Join Tuples if similar initial element
Sometimes, while working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Inp
8 min read
Python - Test if tuple list has Single element
Given a Tuple list, check if it is composed of only one element, used multiple times. Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Output : True Explanation : All elements are equal to 3. Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] Output : False Explanation : All elemen
7 min read
Python - Similar index elements Matrix
Sometimes, while working with data, we can have a problem in which we need to perform the construction of matrix from lists element vertically than horizontally. This kind of application can come in Data Science domains in which we need to construct Matrix from several lists. Lets discuss certain wa
7 min read
Python - Test for strictly decreasing list
The test for a monotonic sequence is a utility that has manifold applications in mathematics and hence every sphere related to mathematics. As mathematics and Computer Science generally go parallel, mathematical operations such as checking for strictly decreasing sequences can be useful to gather kn
5 min read
Python - Similar other index element of K
Given List of elements, other list and K, extract all the similar other list index elements if element is K in List. Input : test_list = [6, 4, 6, 3, 6], arg_list = [7, 5, 4, 6, 3], K = 6 Output : [7, 4, 3] Explanation : 7, 4 and 3 correspond to occurrences of 6 in first list.Input : test_list = [2,
7 min read
Python - Test if any set element exists in List
Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1},
4 min read
Python | Extract similar index elements
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are having similar index values. This kind of problem can come in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loo
6 min read