Reputation: 3
Accept 2 strings S1 and S2. Display all the characters that are common in both the strings. Also, display count of those repeating characters.
So far I'm able to collect two strings and display characters that are common in both the stings, but not able to understand how to display the count of repeating characters.
# Python3 program
MAX_CHAR=26
def printCommon( s1, s2):
a1 = [0 for i in range(MAX_CHAR)]
a2 = [0 for i in range(MAX_CHAR)]
length1 = len(s1)
length2 = len(s2)
for i in range(0,length1):
a1[ord(s1[i]) - ord('a')] += 1
for i in range(0,length2):
a2[ord(s2[i]) - ord('a')] += 1
for i in range(0,MAX_CHAR):
if (a1[i] != 0 and a2[i] != 0):
for j in range(0,min(a1[i],a2[i])):
ch = chr(ord('a')+i)
print (ch, end=' ')
if __name__=="__main__":
s1=input("Enter first string:")
s2=input("Enter second string:")
print("Common Characters in Alphabetical Orders")
printCommon(s1, s2);
How can I collect and display the count of repeating characters?
Upvotes: 0
Views: 54
Reputation: 52832
You can find the intersection (i.e. characters that are present in both) by using the built-in set datatype in Python:
common = set(S1) & set(S2)
You can then count the occurrences of these characters either by using collections.Counter
with both strings and iterating over the common letters, or iterating over the common letters and finding the count for each in S1
and S2
:
import collections
common = set(S1) & set(S2)
c = collections.Counter(S1 + S2)
for char in common:
print(char, c[char])
Upvotes: 1