Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3618108
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T22:42:33+00:00 2026-05-18T22:42:33+00:00

I’m getting a sequence of day of the week. Python code of what I

  • 0

I’m getting a sequence of day of the week. Python code of what I want to do:

def week_days_to_string(week_days):
    """
    >>> week_days_to_string(('Sunday', 'Monday', 'Tuesday'))
    'Sunday to Tuesday'
    >>> week_days_to_string(('Monday', 'Wednesday'))
    'Monday and Wednesday'
    >>> week_days_to_string(('Sunday', 'Wednesday', 'Thursday'))
    'Sunday, Wednesday, Thursday'
    """
    if len(week_days) == 2:
       return '%s and %s' % weekdays
    elif week_days_consecutive(week_days):
       return '%s to %s' % (week_days[0], week_days[-1])
    return ', '.join(week_days)

I just need the week_days_consecutive function (the hard part heh).

Any ideas how I could make this happen?

Clarification:

My wording and examples caused some confusion. I do not only want to limit this function to the work week. I want to consider all days of the week (S, M, T, W, T, F). My apologies for not being clear about that last night. Edited the body of the question to make it clearer.

Edit: Throwing some wrenches into it

Wraparound sequence:

>>> week_days_to_string(('Sunday', 'Monday', 'Tuesday', 'Saturday'))
'Saturday to Tuesday'

And, per @user470379 and optional:

>>> week_days_to_string(('Monday, 'Wednesday', 'Thursday', 'Friday'))
'Monday, Wednesday to Friday'
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T22:42:34+00:00Added an answer on May 18, 2026 at 10:42 pm

    I would approach this problem by:

    • Creating a dict mapping day names to their sequential index
    • Converting my input day names to their sequential indices
    • Looking at the resulting input indices and asking if they are sequential

    Here’s how you can do that, using calendar.day_name, range and some for comprehensions:

    day_indexes = {name:i for i, name in enumerate(calendar.day_name)}
    def weekdays_consecutive(days):
        indexes = [day_indexes[d] for d in days]
        expected = range(indexes[0], indexes[-1] + 1)
        return indexes == expected
    

    A few other options, depending on what you need:

    • If you need Python < 2.7, instead of the dict comprehension, you can use:

      day_indexes = dict((name, i) for i, name in enumerate(calendar.day_name))
      
    • If you don’t want to allow Saturday and Sunday, just trim off the last two days:

      day_indexes = ... calendar.day_name[:-2] ...
      
    • If you need to wrap around after Sunday, it’s probably easiest to just check that each item is one more than the previous item, but working in modulo 7:

      def weekdays_consecutive(days):
          indexes = [day_indexes[d] for d in days]
          return all(indexes[i + 1] % 7 == (indexes[i] + 1) % 7
                     for i in range(len(indexes) - 1))
      

    Update: For the extended problem, I would still stick with they day-to-index dict, but instead I would:

    • Find all the indexes where a run of sequential days stops
    • Wrap the days around if necessary to get the longest possible sequence of days
    • Group the days into their sequential spans

    Here’s code to do this:

    def weekdays_to_string(days):
        # convert days to indexes
        day_indexes = {name:i for i, name in enumerate(calendar.day_name)}
        indexes = [day_indexes[d] for d in days]
    
        # find the places where sequential days end
        ends = [i + 1
                for i in range(len(indexes))
                if (indexes[(i + 1) % len(indexes)]) % 7 !=
                   (indexes[(i) % len(indexes)] + 1) % 7]
    
        # wrap the days if necessary to get longest possible sequences
        split = ends[-1]
        if split != len(days):
            days = days[split:] + days[:split]
            ends = [len(days) - split + end for end in ends]
    
        # group the days in sequential spans
        spans = [days[begin:end] for begin, end in zip([0] + ends, ends)]
    
        # format as requested, with "to", "and", commas, etc.
        words = []
        for span in spans:
            if len(span) < 3:
                words.extend(span)
            else:
                words.append("%s to %s" % (span[0], span[-1]))
        if len(days) == 1:
            return words[0]
        elif len(days) == 2:
            return "%s and %s" % tuple(words)
        else:
            return ", ".join(words)
    

    You might also try the following instead of that last if/elif/else block to get an “and” between the last two items and commas between everything else:

        if len(words) == 1:
            return words[0]
        else:
            return "%s and %s" % (", ".join(words[:-1]), words[-1])
    

    That’s a little different from the spec, but prettier in my eyes.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a JSP page retrieving data and when single or double quotes are
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.