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:
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 an including this index
d1.extend(days[:i]) # append the list form the beginning to this index
return d1
And 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)
Hmm, you are currently only searching for the given weekday and set as result :) You can use the slice ability in python list to do this:
result = days[days.index(weekday):] + days[:days.index(weekdays)]
You don't need to hardcode array of weekdays. It's already available in calendar module.
import calendar as cal
def weekdays(weekday):
start = [d for d in cal.day_name].index(weekday)
return [cal.day_name[(i+start) % 7] for i in range(7)]
Here's more what you want:
def weekdays(weekday):
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
index = days.index(weekday)
return (days + days)[index:index+7]
Every time you run the for loop, the day variable changes. So day is equal to your input only once. Using "Sunday" as input, it first checked if Monday = Sunday, then if Tuesday = Sunday, then if Wednesday = Sunday, until it finally found that Sunday = Sunday and returned Sunday.
Your result
variable is a string
and not a list
object. Also, it only gets updated one time which is when it is equal to the passed weekday
argument.
Here's an implementation:
import calendar
def weekdays(weekday):
days = [day for day in calendar.day_name]
for day in days:
days.insert(0, days.pop()) # add last day as new first day of list
if days[0] == weekday: # if new first day same as weekday then all done
break
return days
Example output:
>>> weekdays("Wednesday")
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
>>> weekdays("Friday")
['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
>>> weekdays("Tuesday")
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']