Open In App

Python | Sorting string using order defined by another string

Last Updated : 27 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples:

Input : pat = "asbcklfdmegnot", str = "eksge" 
Output : str = "geeks"
(after sorting, str becomes "skeeg" and return its reverse)

Input : pat = "mgewqnasibkldjxruohypzcftv", str = "niocgd"
Output : str = "coding"

The idea is to first maintain a dictionary according to the index provided in Pattern and then passing the lambda function(which uses utility of dictionary) into the sort function. Below is the implementation of above idea. 

Python3




# Python program to sort a string and return
# its reverse string according to pattern string
 
# This function will return the reverse of sorted string
# according to the pattern
 
def sortbyPattern(pat, str):
 
    priority = list(pat)
 
    # Create a dictionary to store priority of each character
    myDict = { priority[i] : i for i in range(len(priority))}
 
    str = list(str)
 
    # Pass lambda function as key in sort function
    str.sort( key = lambda ele : myDict[ele])
 
    # Reverse the string using reverse()
    str.reverse()
 
    new_str = ''.join(str)
    return new_str
 
 
if __name__=='__main__':
    pat = "asbcklfdmegnot"
    str =  "eksge"
    new_str = sortbyPattern(pat, str)
    print(new_str)


Output:

geeks

Time Complexity: n*log(n) where n is the length of the string
Auxiliary Space: O(n) where n is length of string


Previous Article
Next Article

Similar Reads

Sort the array of strings according to alphabetical order defined by another string
Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Note: str and every string in strArr[] consists of only lower case alphabets. Examples: Input: str = "fguecbdavwyxzhijklmnopqrst", strArr[] = {"geeksforgeeks", "is", "the", "best", "place", "for", "learning"} Output
5 min read
Sorting objects of user defined class in Python
The following article discusses how objects of a user-defined class can be arranged based on any of the variables of the class, which obviously will hold some value for every object. So far, we are aware of how we can sort elements of a list, the concept here is more or less the same as, except it is a step forward or we can say it is an advanced v
4 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Different ways of sorting Dictionary by Values and Reverse sorting by values
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse s
15+ min read
Python - Check if String Contain Only Defined Characters using Regex
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Explanation: The Input string only consists of charac
2 min read
Sorting List of Dictionaries in Descending Order in Python
Sorting is one of the most common things in Python and is used in day-to-day programming. In this article, we will sort the list of dictionaries in descending order in Python. Sorting The List of Dictionaries In Descending OrderThere are different methods to Sort The List Of Dictionaries In Descending Order using Python. Below we are explaining all
3 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python Python throws errors and
4 min read
Python | Scope resolution when a function is called or defined
Python resolves the scope of the parameters of a function in two ways: When the function is definedWhen the function is called When the function is defined Consider this sample program which has a function adder(a, b) which adds an element a to the list b and returns the list b. The default value of b is [1, 8, 11]. Code : C/C++ Code def adder(a, b
3 min read
Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functions that readily come with Python are called built
6 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
three90RightbarBannerImg