Return a list of weekdays, starting with given weekday

后端 未结 9 2344
情书的邮戳
情书的邮戳 2021-02-07 23:53

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:

9条回答
  •  不思量自难忘°
    2021-02-08 00:37

    Another approach using the standard library:

    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
            'Sunday']
    def weekdays(weekday):
      n = days.index(weekday)
      return list(itertools.islice(itertools.cycle(days), n, n + 7))
    

    Itertools is a bit much in this case. Since you know at most one extra cycle is needed, you could do that manually:

    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
            'Sunday']
    days += days
    def weekdays(weekday):
      n = days.index(weekday)
      return days[n:n+7]
    

    Both give the expected output:

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

提交回复
热议问题