Python - Characters occurring in multiple Strings
Last Updated :
24 Apr, 2023
Sometimes, while working with Python strings, we can have problem in which we need to extract the characters which have occurrences in more than one string in string list. This kind of problem usually occurs in web development and Data Science domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using Counter() + set() This is one of the ways in which this task can be performed. In this, we check for all the strings and compute the character frequency in each string and return the character which have more than one string occurrence.
Python3
# Python3 code to demonstrate working of
# Characters occurring in multiple Strings
# Using Counter() + set()
from itertools import chain
from collections import Counter
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
# printing original list
print("The original list is : " + str(test_list))
# Characters occurring in multiple Strings
# Using Counter() + set()
temp = (set(sub) for sub in test_list)
cntr = Counter(chain.from_iterable(temp))
res = [chr for chr, count in cntr.items() if count >= 2]
# printing result
print("Characters with Multiple String occurrence : " + str(res))
Output :
The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs'] Characters with Multiple String occurrence : ['g', 'e', 'f', 's']
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the Counter() + set() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using list comprehension + Counter() + set() This is one of the way in which this task can be performed. In this, we perform similar task as above, the difference is that we perform in compact and one-liner way using list comprehension.
Python3
# Python3 code to demonstrate working of
# Characters occurring in multiple Strings
# Using list comprehension + Counter() + set()
from itertools import chain
from collections import Counter
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
# printing original list
print("The original list is : " + str(test_list))
# Characters occurring in multiple Strings
# Using list comprehension + Counter() + set()
res = [key for key, val in Counter([ele for sub in test_list
for ele in set(sub)]).items()
if val > 1]
# printing result
print("Characters with Multiple String occurrence : " + str(res))
Output :
The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs'] Characters with Multiple String occurrence : ['g', 'e', 'f', 's']
Time complexity: O(N*M), where N is length of test_list and M is number of characters of string in test_list
Auxiliary Space: O(K), where K is length of res list.
Method #3 : Using dict+ for loop().
In this code, we first create an empty dictionary called char_counts to store the character counts. We then iterate over each string in the list and, for each character in the string, either increment the count for the character in the dictionary or add the character to the dictionary with a count of 1.
After counting the characters in all the strings, we iterate over the dictionary and add any character that occurs in more than one string to the result set.
At the end of the loop, the result set will contain the characters that occur in multiple strings. then convert the set into list and We then print out the result using the print() function.
Python3
# Sample list of strings
strings_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
# Create a dictionary to store the character counts
char_counts = {}
l=[]
# Iterate over each string in the list
for s in strings_list:
# Iterate over each character in the string
for c in s:
# If the character is already in the dictionary, increment its count
if c in char_counts:
char_counts[c] += 1
# Otherwise, add the character to the dictionary with a count of 1
else:
char_counts[c] = 1
# Find the characters that occur in multiple strings
result = set()
for c, count in char_counts.items():
if count > 1:
result.add(c)
#convert set to list
z=list(result)
# Print the characters with multiple string occurrence
print('Characters with Multiple String occurrence:', z)
OutputCharacters with Multiple String occurrence: ['e', 'g', 'f', 's']
Time complexity: O(N*M)
Auxiliary Space: O(K)
Method #4 : Using list(),set(),count() methods
Approach
- Concatenated all the strings using for loop and += operator
- Created a list with all unique characters of concatenated string(using list(),set() methods)
- Now check whether the each character of newly created list is occurring more than once using count()
- If occurs more than once append such characters to output list
- Display output list
Python3
# Python3 code to demonstrate working of
# Characters occurring in multiple Strings
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
# printing original list
print("The original list is : " + str(test_list))
# Characters occurring in multiple Strings
res=[]
x=""
for i in test_list:
x+=i
y=list(set(x))
for i in y:
if x.count(i)>1:
res.append(i)
# printing result
print("Characters with Multiple String occurrence : " + str(res))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs']
Characters with Multiple String occurrence : ['s', 'g', 'e', 'f']
Time Complexity: O(N*N)
Auxiliary Space : O(N)
Similar Reads
Python - Characters Index occurrences in String Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read
Remove Multiple Characters from a String in Python Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Letâs explore the different ways to achieve this in det
2 min read
Python | Replace multiple occurrence of character by single Given a string and a character, write a Python program to replace multiple occurrences of the given character by a single character. Examples: Input : Geeksforgeeks, ch = 'e' Output : Geksforgeks Input : Wiiiin, ch = 'i' Output : WinReplace multiple occurrence of character by singleApproach #1 : Nai
4 min read
Iterate over characters of a string in Python In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Letâs explore this approach.Using for loopThe simplest way to iterate over the characters in
2 min read
Split String into List of characters in Python We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read
Python program to find occurrence to each character in given string Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them. Method #1: Using set() + count() Iterate over the set converted string and get the count
5 min read
Python - Expand Character Frequency String Given a string, which characters followed by its frequency, create the appropriate string. Examples: Input : test_str = 'g7f2g3i2s2b3e4' Output : gggggggffgggiissbbbeeee Explanation : g is succeeded by 7 and repeated 7 times. Input : test_str = 'g1f1g1' Output : gfg Explanation : f is succeeded by 1
4 min read
Count the number of characters in a String - Python The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this.Using len()len() is
2 min read
Check if string contains character - Python We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True.Using in Operatorin operator is the easiest way to check if a c
2 min read
Python - Custom Consecutive character repetition in String Given a String, repeat characters consecutively by number mapped in dictionary. Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 3} Output : GGGeekkkkksss444GGGeekkkkksss Explanation : Each letter repeated as per value in dictionary.Input : test_str = 'Geeks4G
4 min read