Hi Programmers,
In todays session we will try to solve a very unique and mostly asked question in interview round between the experience of 2 to 5 years range.
So the problem is there will be a string "wed tues sat sun fri thurs mon" like this and you have to sort it in the below manner.
Input: "wed tues sat sun fri thurs mon"
Output: "mon tues wed thurs fri sat sun"
So we will start our coding here:
m = ["Mon", "Tue", "Wed", "Thu", "Fri"]
n = ["Tue", "Wed", "Mon", "Thu", "Fri", "Tue", "Mon", "Fri"]
print(sorted(n, key=m.index))
['Mon', 'Mon', 'Tue', 'Tue', 'Wed', 'Thu', 'Fri', 'Fri']
OR
d = {name:val for val, name in enumerate(m)}
print(d)
{'Fri': 4, 'Thu': 3, 'Wed': 2, 'Mon': 0, 'Tue': 1}
print(sorted(n, key=d.get))
['Mon', 'Mon', 'Tue', 'Tue', 'Wed', 'Thu', 'Fri', 'Fri']
This could be the simplest solution for this type of problem.
Top comments (0)