Python code to print common characters of two strings alphabetically

Counters | Python Methods and Functions | String Variables

Examples:

 Input: string1: geeks string2: forgeeks Output: eegks Explanation: The letters that are common between the two strings are e (2 times), k (1 time) and s (1 time). Hence the lexicographical output is "eegks" Input: string1: hhhhhello string2: gfghhmh Output: hhh 

This problem has an existing solution, please refer to the link Print common characters of two strings in alphabetical order . We'll solve this problem in python using the

# Function for printing common characters of two lines
# alphabetically

from collections import Counter

 

def common (str1, str2):

 

  # convert both lines to a counter dictionary

dict1 = Counter (str1)

dict2 = Counter (str2)

 

# take the intersection of these dictionaries

commonDict = dict1 & amp; dict2

 

if len (commonDict) = = 0 :

  print - 1

return

 

# get a list of shared items

commonChars = list (commonDict.elements ())

 

  # sort the list in ascending order to print the resulting one

# alphabetical string

commonChars = sorted (commonChars)

 

# combine non-whitespace characters for production

# resulting string

print '' .join (commonChars)

 
# Driver program

if __ name__ = = " __ main__ " :

str1 = ' geeks'

str2 = 'forgeeks'

  common (str1, str2)

Output:

 eegks