Sort an array of strings based on the given order | Python3 program to sort an array of strings based on the given order ; For storing priority of each character ; Custom comparator function for sort ; Loop through the minimum size between two words ; Check if the characters at position i are different , then the word containing lower valued character is smaller ; When loop breaks without returning , it means the prefix of both words were same till the execution of the loop . Now , the word with the smaller size will occur before in sorted order ; Function to print the new sorted array of strings ; Mapping each character to its occurrence position ; Sorting with custom sort function ; Printing the sorted order of words ; Driver code
from functools import cmp_to_key NEW_LINE mp = { } NEW_LINE def comp ( a , b ) : NEW_LINE INDENT for i in range ( min ( len ( a ) , len ( b ) ) ) : NEW_LINE INDENT if ( mp [ a [ i ] ] != mp [ b [ i ] ] ) : NEW_LINE INDENT if mp [ a [ i ] ] < mp [ b [ i ] ] : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT DEDENT if ( len ( a ) < len ( b ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT def printSorted ( words , order ) : NEW_LINE INDENT for i in range ( len ( order ) ) : NEW_LINE INDENT mp [ order [ i ] ] = i NEW_LINE DEDENT words = sorted ( words , key = cmp_to_key ( comp ) ) NEW_LINE for x in words : NEW_LINE INDENT print ( x , end = " ▁ " ) NEW_LINE DEDENT DEDENT words = [ " word " , " world " , " row " ] NEW_LINE order = " worldabcefghijkmnpqstuvxyz " NEW_LINE printSorted ( words , order ) NEW_LINE