2013-01-20 43 views
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语句的情况下解决此问题?未使用IF语句

顺便说一下,星期日是1,星期一是2,....饱和是7

回答

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 
+0

你能解释一点请!即时通讯新的蟒蛇,我不明白如何只是增加或有可以解决我的问题 – user1864828

+0

零是布尔错误,所以0或7给7.这就是说,如果你不能使用'if',比使用'或'可以限定作为作弊:) –

3

试试这个:

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

如何

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