Search code examples
pythoncalendarweekday

Return a list of weekdays, starting with given weekday


My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this:

>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

So far I've come up with this one:

def weekdays(weekday):
    days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
            'Sunday')
    result = ""
    for day in days:
        if day == weekday:
            result += day
    return result

But this prints the input day only:

>>> weekdays("Sunday")
'Sunday'

What am I doing wrong?


Solution

  • def weekdays(day):
        days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        i=days.index(day)   # get the index of the selected day
        d1=days[i:]         # get the list from and including this index
        d1.extend(days[:i]) # append the list from the beginning to this index
        return d1
    

    If you want to test that it works:

    def test_weekdays():
        days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        for day in days:
            print weekdays(day)