Sebastian Ferreira
Sebastian Ferreira

Reputation: 43

Python: How to find a day week given the starting day and the amount of days to increase?

I have to build a time calculator as an assigment.

One of the given requeriments is to tell which day of the week will the resulting time be.

For example: 12:00 AM Monday + 24:00 should return 12:00 AM Tuesday

And the code I currently use does that, but I found a bug that suggest I'm approaching this wrong, so I would like to get your help to notice what can I do about this.

When I get the same day I started, instead of the index being 0 it is 7, and I get the list index out of range error.

This is my function

def dayFind(startDay, increment):

    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    week = len(days)
    index = days.index(startDay)

    day = days[index + increment % 7]
       
    return day

    print(dayFind("Tuesday", 20)) # Returns IndexError: list index out of range

Upvotes: 0

Views: 73

Answers (2)

Khushal
Khushal

Reputation: 779

Replace :

day = days[index + increment % 7]

with :

index = index + increment//24
if index//7 >=1:
    index = index %7
day = days[index]

increment//24 return an int rounded to greatest integer less than the quotient.

For example when input is 20 the floor division gives 0 which means the day should not change

when input is 40 the floor division gives 1 so only 1 day is incemented.

Upvotes: 0

Matthew FW
Matthew FW

Reputation: 106

The mod (%) operator has the same precedence as multiplication, so it gets evaluated before your addition. You should write days[(index + increment) % 7].

Upvotes: 1

Related Questions