please read the code first; i am trying to get familiar with custom sorting so I need help understanding how 'eksge' is sorted into 'geeks' and what's happening inside def sortbypattern function, how 'g' is made to appear first then followed by 'e' ,'e' ,'k' ,'s'; can anyone explain me the algorithm and a dry run
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
I don't know what the use of such a function may be, but it's rather simple:
pat
, then priority
(which by the way is a totally useless step), and finally myDict
specify the expected ordering of the chars sort
sorts your string comparing each char based on the priority from myDict
instead of a standard alphabetical ordering The sortbyPattern
function takes pattern
and the string
to be sorted as parameters. The pattern
is working as a priority list here. The less the index number the lower the priority.
Inside the function, the priority
is a list of the characters in the pattern
. The pattern given is asbcklfdmegnot
. If you print priority
, you'll get:
['a', 's', 'b', 'c', 'k', 'l', 'f', 'd', 'm', 'e', 'g', 'n', 'o', 't']
So, as the lower the index, the lower the priority, we can make a dict having priority score similar to their corresponding index. That is what done in the line myDict = { priority[i] : i for i in range(len(priority))}
. The dict looks like this:
{'a': 0, 's': 1, 'b': 2, 'c': 3, 'k': 4, 'l': 5, 'f': 6, 'd': 7, 'm': 8, 'e': 9, 'g': 10, 'n': 11, 'o': 12, 't': 13}
Now, str = list(str)
is called to make a list of characters inside the input str
variable, eksge
. Then str.sort( key = lambda ele : myDict[ele])
is applied. This basically sorted the str
based on the value of each character in str
in the dict myDict
. So the str
is sorted in ascending order based on the value of each character it got from myDict
. In this situation, we got in str
:
['s', 'k', 'e', 'e', 'g']
Finally, str.reverse()
made the str
reversed, hence str
in desired order.
Point to be noted, if you had done a reverse=True
in the sort parameter, you wouldn't need to call that str.reverse()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.