DEV Community

Abdulla Ansari
Abdulla Ansari

Posted on • Edited on

3 2

Sort Weekdays in Python | Example "wed tues sat sun fri thurs mon"

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']

Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

This could be the simplest solution for this type of problem.

Buy me coffee

My other Blog Website over Technology

My YouTube Vlog Channel

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more