我知道写这篇文章肯定有一种更简单的方法,但我陷入了过于复杂的心态,而不只是跟随Python的禅宗。请帮我简化一下。
给定一周中编码为0=Sun、1=Mon、2=Tue、...6=Sat的一天,以及指示我们是否正在度假的布尔值,则返回表单"7:00“的字符串,指示闹钟何时应响。工作日,闹钟应该是7:00,周末应该是10:00。除非我们在度假--那么在平日应该是"10:00“,周末应该是”休息“。alarm_clock(1,False)→'7:00‘alarm_clock(5,False)→'7:00’alarm_clock(0,False)→'10:00‘
def alarm_clock(day, vacation):
weekend = "06"
weekdays = "12345"
if vacation:
if str(day) in weekend:
return "off"
else:
return "10:00"
else:
if str(day) in weekend:
return "10:00"
else:
return "7:00"发布于 2015-07-10 15:39:10
我不认为它比这简单得多(Pythonic,易于阅读,性能好到永远不会成为瓶颈):
def alarm_clock(day, vacation):
weekend = int(day) in (0, 6)
if weekend and vacation:
return 'off'
elif weekend or vacation:
return '10:00'
return '7:00'在创建了一个weekend布尔值之后,我想出了这个问题,然后检查alarm_clock应该具有的返回值:
return_values = {
# (weekend, vacation): Return value,
(True, True): 'off',
(True, False): '10:00',
(False, True): '10:00',
(False, False): '7:00'
}正如您所看到的,如果两者都是True (if weekend and vacation:),那么我们应该返回'off',如果其中一个是True (if weekend or vacation:),则应该返回10:00,而不管哪一个。否则返回7:00
发布于 2015-07-10 15:04:05
这保持了相同的逻辑,它只是消除了对如此简单的返回语句的需求。
def alarm_clock(day, vacation):
weekend = "06"
if vacation:
return "off" if str(day) in weekend else "10:00"
else:
return "10:00" if str(day) in weekend else "7:00"我会进一步改进它,增加一个检查,您输入一个数字0-6。
if not (0 <= day <= 6):
return "-:--"发布于 2015-07-10 14:55:52
那麽:
(str(day) in weekend)替换(0 == day %6),但是很难理解代码:
def alarm_clock(day, vacation):
weekend = "06"
if vacation and (str(day) in weekend):
return "off"
else:
if not (str(day) in weekend):
return "7:00"
return "10:00"更隐秘的版本:
def alarm_clock(day, vacation):
if vacation and 0 == day % 6:
return "off"
else:
if 0 != day % 6:
return "7:00"
return "10:00"https://codereview.stackexchange.com/questions/96478
复制相似问题