Sort Weekdays in Python | Example “wed Tues sat sun Fri Thurs mon”

Abdulla Ansari
1 min readNov 17, 2022

--

Hi Programmers,

In today's session, we will try to solve a very unique and mostly asked question in the 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 a below manner.

Input: “Wed Tues sat sun Fri Thur's 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.

Buy me coffee

My other Blog Website over Technology

My YouTube Vlog Channel

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Abdulla Ansari
Abdulla Ansari

Written by Abdulla Ansari

Connect with me to enhance yourself from a college guy to a senior software engineer in tech like python, javascript and now generative ai

No responses yet

Write a response