Using Python, Write a function to return all the common characters in two input strings. The return must be a list of characters and only unique characters will be returned. For example, given 'abcdefg' and 'define', the function will return ['d', 'e', 'f'] (note e only appears once). (Hint: Use the in operator.)
Solution :
We can do this program in very simple manner using set operations of python.if we consider both time and space complexities this solution is the very efficient .
Code:
input_string1=input("Enter the String 1: ") #taking first string
from user
input_string2=input("Enter the String 2: ") #taking second string
from user
set1=set(input_string1) #convert the input_string1 to set
datatype
set2=set(input_string2) #convert the input_string2 to set
datatype
final_output=list(set1 & set2) #apply intersection operation
between set1 and set2 using & operator and store into
list
final_output.sort() #sort the charcaters in alphabetical order to
get the desired output
print ("The common character in both strings are : ") #print common
characters are
print(final_output) #print final list
Code and Output Screenshots:
Note : if you have any queries please post a comment thanks a lot..always available to help you...
Get Answers For Free
Most questions answered within 1 hours.