user1864828
user1864828

Reputation: 359

without using IF statement

def get_weekday(d1, d2):
    ''' (int, int) -> int
    The first parameter indicates the current day of the week, and is in the 
    range 1-7. The second parameter indicates a number of days from the current 
    day, and that could be any integer, including a negative integer. Return 
    which day of the week it will be that many days from the current day.
    >>> get_weekday(0,14)
    7
    >>> get_weekday(0,15)
    1
    '''
    weekday = (d1+d2) % 7
    if weekday == 0:
        weekday = 7
    return weekday

how can I solve this without using the if statement?

by the way, sunday is 1, monday is 2,.... sat is 7

Upvotes: 1

Views: 169

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

use the or condition:

weekday = (d1+d2) % 7 or 7
return weekday

The statements in or condition are evaluated from left to right until a True value is not found, otherwise the last value is returned.

so here if the first part is 0 then it returns 7.

In [158]: 14%7 or 7       # 14%7 is 0, i.e a Falsy value so return 7
Out[158]: 7

In [159]: 15%7 or 7       #15%7 is  1, i.e a Truthy value so exit here and return 15%7
Out[159]: 1

#some more examples
In [161]: 0 or 0 or 1 or 2
Out[161]: 1

In [162]: 7 or 0
Out[162]: 7

In [163]: False or True
Out[163]: True

Upvotes: 0

user1995314
user1995314

Reputation:

How about

weekday = (d1-1+d2) % 7 + 1

Upvotes: 4

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

Try this:

weekday = ((d1+d2-1) % 7) + 1

Upvotes: 3

Related Questions