不使用IF语句

时间:2013-01-20 22:45:59

标签: python

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。

3 个答案:

答案 0 :(得分:4)

怎么样

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

答案 1 :(得分:3)

试试这个:

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

答案 2 :(得分: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