Python – Characters which Occur in More than K Strings
Sometimes, while working with Python, we have a problem in which we compute how many characters are present in string. But sometimes, we can have a problem in which we need to get all characters that occur in atleast K Strings. Let’s discuss certain ways in which this task can be performed. Method #1 : Using set() + Counter() + items() + loop The combination of above functions can be used to perform this particular task. In this, we find the count using Counter and set is used to limit the character duplicacy.
Python3
# Python3 code to demonstrate # Characters which Occur in More than K Strings # using set() + Counter() + loop + items() from collections import Counter from itertools import chain def char_ex(strs, k): temp = ( set (sub) for sub in strs) counts = Counter(chain.from_iterable(temp)) return { chr for chr , count in counts.items() if count > = k} # Initializing list test_list = [ 'Gfg' , 'ise' , 'for' , 'Geeks' ] # printing original list print ("The original list is : " + str (test_list)) # Initializing K K = 2 # Characters which Occur in More than K Strings # using set() + Counter() + loop + items() res = char_ex(test_list, K) # printing result print ("Filtered Characters are : " + str (res)) |
The original list is : ['Gfg', 'ise', 'for', 'Geeks'] Filtered Characters are : {'e', 'G', 's', 'f'}
Time complexity : O(nm) where n is the number of strings in the list and m is the average length of the strings.
Auxiliary Space complexity : O(nm) as well, as it uses a set and a Counter object to store characters and their counts.
Method #2 : Using dictionary comprehension + set() + Counter() The combination of these functions perform this task in similar way as above. The difference is just that we use dictionary comprehension to give a compact solution to problem.
Python3
# Python3 code to demonstrate # Characters which Occur in More than K Strings # using set() + Counter() + dictionary comprehension from collections import Counter # Initializing list test_list = [ 'Gfg' , 'ise' , 'for' , 'Geeks' ] # printing original list print ("The original list is : " + str (test_list)) # Initializing K K = 2 # Characters which Occur in More than K Strings # using set() + Counter() + dictionary comprehension res = {key for key, val in Counter([ele for sub in test_list for ele in set (sub)]).items() if val > = K} # printing result print ("Filtered Characters are : " + str (res)) |
The original list is : ['Gfg', 'ise', 'for', 'Geeks'] Filtered Characters are : {'e', 'G', 's', 'f'}
Time complexity : O(n), where n is the total number of characters in the test_list.
Auxiliary Space : O(n), as the Counter object stores the count of all characters in the test_list.
Please Login to comment...