HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Alarm clock printing

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
alarmprintingclock

Problem

I know there must be an easier way to write this but I'm stuck in over-complicating mindset instead of just following the Zen of Python. Please help me simplify this.


Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and
a boolean indicating if we are on vacation, return a string of the
form "7:00" indicating when the alarm clock should ring. Weekdays, the
alarm should be "7:00" and on the weekend it should be "10:00". Unless
we are on vacation -- then on weekdays it should be "10:00" and
weekends it should be "off".

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"

Solution


  • You don't use weekdays.



  • You can have two return statements. (Shown below).



This keeps the same logic, it just removes the need for so meany return statements.

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"


I would improve it further by adding a check, that you enter a number 0-6.

if not (0 <= day <= 6):
    return "-:--"

Code Snippets

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"
if not (0 <= day <= 6):
    return "-:--"

Context

StackExchange Code Review Q#96478, answer score: 7

Revisions (0)

No revisions yet.