1
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

如何在不使用 if 语句的情况下解决这个问题?

顺便说一句,星期日是 1,星期一是 2,.... 星期六是 7

4

3 回答 3

4

怎么样

weekday = (d1-1+d2) % 7 + 1
于 2013-01-20T22:49:39.727 回答
3

尝试这个:

weekday = ((d1+d2-1) % 7) + 1
于 2013-01-20T22:49:19.670 回答
0

使用or条件:

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

条件中的语句or从左到右求值,直到True没有找到值,否则返回最后一个值。

所以在这里,如果第一部分是 0,那么它返回 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
于 2013-01-20T22:48:44.513 回答