

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python code to print common characters of two Strings in alphabetical order
Two user input strings are given, our task is to print all the common characters in alphabetical order.
Example
Input: string1: python string2: program Output: op
Explanation
The letters that are common between the two strings are o (1 times), p (1 time)
Algorithm
Step 1: first we take two input string. Step 2: next we will do to convert these two strings into counter dictionary. Step 3: Now find common elements between two strings using intersection ( ) property. Step 4: Resultant will also be a counter dictionary having common elements as keys and their common frequencies as value. Step 5: Use elements () method of the counter dictionary to expand the list of keys by their frequency number of times. Step 6: sort list in ascending order to print a resultant string in alphabetical order. Step 7: join characters without space to produce resultant string.
Example Code
from collections import Counter def common(str1,str2): d1 = Counter(str1) d2 = Counter(str2) cdict = d1 & d2 if len(cdict) == 0: print -1 return cchars = list(cdict.elements()) cchars = sorted(cchars) print ("Common characters are ::>",''.join(cchars) ) # Driver program if __name__ == "__main__": s1 = input("Enter first string") s2 = input("Enter second string") common(s1, s2)
Output
Enter first string python Enter second string program Common characters are ::> op
- Related Questions & Answers
- Java code to print common characters of two Strings in alphabetical order
- Print common characters of two Strings in alphabetical order in C++
- Count common characters in two strings in C++
- Python – Extract Strings with Successive Alphabets in Alphabetical Order
- Common Words in Two Strings in Python
- Check if the characters of a given string are in alphabetical order in Python
- Order strings by length of characters IN mYsql?
- Python program to print all the common elements of two lists.
- Removing n characters from a string in alphabetical order in JavaScript
- Program to find size of common special substrings of two given strings in Python
- Python program to remove words that are common in two Strings
- Sorting numbers in ascending order and strings in alphabetical order in an array in JavaScript
- Print the kth common factor of two numbers
- Sort the array of strings according to alphabetical order defined by another string in C++
- Greatest Common Divisor of Strings in Python
Advertisements