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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay