Why doesn't Python read my boolean Vacation? - python

I was trying this excercise on Codebat:
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. On 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".
def alarm_clock(day, vacation):
vacation_weekday = vacation and day in range(1,6)
vacation_weekend = day == 0 and day == 6 and vacation
if day in range(1,6):
return "7:00"
elif day == 0 or day == 6:
return "10:00"
elif vacation_weekday:
return "10:00"
elif vacation_weekend:
return "off"
If i run print(alarm_clock(1,True)) it returns "7:00" instead of "10:00". Can somebody help me ?

Your first if statement checks if day in range(1, 6). If day is 1 that will always be true. Since the first condition matched, none of the elif conditions are even executed. (Additionally, since you return immediately, no other code in the function is executed after that point either.)
You probably want to rearrange the if statements so that you check the special cases first, and then the general cases. Alternatively, precompute a weekend and/or weekday boolean value and then express all the conditions explicitly:
def alarm_clock(day, vacation):
weekday = 1 <= day <= 5
weekend = not weekday
if weekend and vacation:
return "off"
if weekend and not vacation:
return "10:00"
if weekday and vacation:
return "10:00"
if weekday and not vacation:
return "7:00"
Or even, using a ternary expression:
def alarm_clock(day, vacation):
weekday = 1 <= day <= 5
if vacation:
return "10:00" if weekday else "off"
return "7:00" if weekday else "10:00"

Here is how you should have rewritten your code to evaluate it properly:
def alarm_clock(day, vacation):
weekday_alarm_clock = "7:00 AM"
weekend_alarm_clock = "10:00 AM"
if vacation:
weekday_alarm_clock = "10:00 AM"
weekend_alarm_clock = "off"
if day > 0 and day < 6:
return weekday_alarm_clock
else:
return weekend_alarm_clock
As you can see here, if we are on vacation then we set out weekday alarm clock to 10:00. and turn off the weekend clock. it is not Sunday or Saturday and vacation is not true then we return our normal clock. Else its the weekend and its not vacation and we return our normal weekend alarm clock
Now the output I receive when using print(alarm_clock(1,True))is 10:00 AM as expected

My approach would be a little complex:
def alarm_clock(day, vacation):
weekend = [6,7]
if day not in weekend and vacation is True:
return '10:00 AM'
elif day in weekend and vacation is True:
return 'off'
elif day in weekend and vacation is False:
return '10:00 AM'
elif day not in weekend and vacation is False:
return '7:00 AM'
else:
return 'off'
print(alarm_clock(day, vacation))

Related

Using both OR, AND in an IF-statement - Python

def alarm_clock(day, vacation):
if day == 0 or day == 6 and vacation != True:
return "10.00"
else:
return "off"
print(alarm_clock(0, True))
Why does this return "10.00"? In my mind it should return "off". Yes, day is equal to 0, but vacation is True, and the IF-statements first line states that it should only be executed if vacation is not True.
In Python and binds tighter than or. So your statement is equivalent to this:
if day == 0 or (day == 6 and vacation != True):
To get the correct result you must parenthesize the precedence yourself:
if (day == 0 or day == 6) and vacation != True:
What you probably want is this:
def alarm_clock(day, vacation):
if (day == 0 or day == 6) and vacation != True:
return "10.00"
else:
return "off"
print(alarm_clock(0, True))

Program not working for tuesday but working for sunday

I am learning python using a book called How to think like a computer scientist. There they gave an exercise:
Write a function that helps answer questions like “‘Today is Wednesday.
I leave on holiday in 19 days time. What day will that be?”’
So the function must take a day name and a delta argument — the number of days
to add — and should return the resulting day name:
test(day_add("Monday", 4) == "Friday")
test(day_add("Tuesday", 0) == "Tuesday")
test(day_add("Tuesday", 14) == "Tuesday")
test(day_add("Sunday", 100) == "Tuesday")
Hint: use the first two functions written above to help you write this one
Can your day_add function already work with negative deltas? For example, -1 would be yesterday, or -7 would be a week ago:
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
I have written this program
import sys
def test(did_pass):
'''prints result of test at last'''
linenum=sys._getframe(1).f_lineno #gets call line
if did_pass:
msg='Test at line {0} PASS'.format(linenum)
else:
msg=('Test at line {0} FAIL.'.format(linenum))
print(msg)
def day_name(x):
'''converts day number to day'''
if x==0:
return 'Sunday'
elif x==1:
return 'Monday'
elif x==2:
return 'Tuesday'
elif x==3:
return 'Wednesday'
elif x==4:
return 'Thursday'
elif x==5:
return 'Friday'
elif x==6:
return 'Saturday'
else:
return
def day_num(y):
'''converts day to day number'''
if y=='Sunday':
return 0
elif y=='Monday':
return 1
elif y=='Tuesday':
return 2
elif y=='Wednesday':
return 3
elif y=='Thursday':
return 4
elif y=='Friday':
return 5
elif y=='Saturday':
return 6
else:
return
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result=(stay)%7
answer=(result)+(day_num(today))
return day_name(answer)
def test_suite():
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
test_suite()
so the first function is to test my program for bugs. The problem is first two tests are clear but last test fails even if it has the same negative value as the first two. I want to know what is the mistake which makes the first two tests pass but later fail. Im beginner so kindly use some easy statements.
Your calculations are wrong. Following How to debug small programs Change your code to
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result = stay % 7
answer = result + day_num(today)
print(result, day_num(today), day_name(answer)) # DEBUG your code
return day_name(answer)
Output:
6 0 Saturday
Test at line 34 PASS
0 0 Sunday
Test at line 35 PASS
5 2 None # analyze this and fix it.
Test at line 36 FAIL.

How do I solve the leap year function in Python for Hackerrank?

I cannot for the life of me solve this challenge on Hackerrank. The closest I got it was to 4/6 passes.
Rules:
In the Gregorian calendar three criteria must be taken into account to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
Code:
def is_leap(year):
leap = False
# Write your logic here
if year%400==0 :
leap = True
elif year%4 == 0 and year%100 != 0:
leap = True
return leap
year = int(input())
print(is_leap(year))
You forgot the ==0 or !=0 which will help understand the conditions better. You don't have to use them, but then it can cause confusion maintaining the code.
def is_leap(year):
leap = False
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
a shorter version would be:
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
You can try this
def is_leap():
leap = False
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
leap = True
return leap
This code might be easy for some of the people to wrap their head around
def is_leap(year):
leap = False
# Write your logic here
if year%4==0:
leap=True
if year%100==0:
leap=False
if year%400==0:
leap=True
return leap
year = int(input())
print(is_leap(year))
If we split the question point by point.
Actual question:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
Explaining it : If a year is divided by 4, then its a leap year.
If this is divided by 100 but not 400 after being divisible by 4,
then its not a leap year.
If this is divisible by 4, 100 ,400 , then its a leap year.
Basically, nested if
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
leap =True
else:
leap=False
else:
leap=True
else:
leap=False
return leap
def is_leap(year):
leap=False
check =lambda year : year :year%4==0 and (year%400==0 or year%100!=0)
leap=check(year)
return leap
year =int(input())
print(is_leap(year))
def is_leap(year):
leap = False
if year%4 == 0:
if(year%100 != 0 or year%400 == 0):
leap = True
return leap
def is_leap(year):
leap = False
# Write your logic here
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 100 == 0 and year % 400 != 0:
leap = False
elif year % 400 == 0:
leap = True
elif year % 4 != 0:
leap = False
return leap
year = int(raw_input())
print is_leap(year)
def is_leap(year):
leap = False
if(year%4==0):
#century year check
if(year%100==0):
#century leap year check
if(year%400==0):
leap=True
else:
leap=True
return leap
if year%4==0 and year%100==0 and year%400==0:
return True
elif year%4==0 and year%100!=0 and year%400!=0:
return True
else:
return False
n = [int(input("Enter a year in four digit: "))]
a = list(map(lambda x: "is a Leap year" if x%4 == 0 or ( x % 100 != 0 or x % 400 == 0) else "is not a Leap year" , n))
print(f"{n[0]} {a[0]}")
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 != 0:
leap = True
elif year % 400 == 0 and year % 100 == 0:
leap = True
return leap
I just try with this:
def is_leap(year):
leap = False
# Write your logic here
if (year%4 ==0 and year%100 !=0) or year%400 ==0:
leap = True
else:
leap = False
return leap
year = int(input())
print(is_leap(year))
if year can be evenly divided by 4 and 400 is True but if it can be evenly divided by 100 is False
#simplest solution for beginner
n = int(input('Enter year to check if it is leap year.'))
if n % 4 == 0 and n%100 != 0:
leap = 'True'
elif n % 100 == 0 and n%400==0:
leap = 'True'
else:
leap = 'False'
print('the entered year is,'+leap)
This would be my solution for the problem. We want the number to be divisible with 4 no matter what. So year % 4 will need to be true for the output to be bool True as well. Then we have to consider if the number which is divisible with 4 can be divided to 400. If the number is divisible to 100 but not 400 it should give us bool False. That is why we should check divisibility to 400 and non-divisibility to 100 together and use or statement.
def is_leap(year):
leap = False
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return not leap
else:
return leap
year = int(input())
print(is_leap(year))
def is_leap(year):
leap = False
# Write your logic here
if (year%4 ==0):
if (year%100 == 0) and (year%400 ==0):
leap = True
elif(year%100 == 0) and (year%400 !=0):
leap = False
else:
leap = True
else:
leap = False
return leap
year = int(input())
HackerRank Problem - An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap years.
Solution is the below Python Code.
def is_leap(year):
leap = False
# Write your logic here
if (year % 4 == 0) and (year % 100 != 0):
# Note that in your code the condition will be true if it is not..
leap = True
elif (year % 100 == 0) and (year % 400 != 0):
leap = False
elif (year % 400 == 0):
# For some reason here you had False twice
leap = True
else:
leap = False
return leap
year = int(input())
print(is_leap(year))
Try this #Charles Thompson, this passed all test cases for me.
def is_leap(year):
leap = False
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
leap = True
else:
leap = False
else:
leap = True
return leap
def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
return True
elif year %4 == 0 and year % 100! = 0 and year % 400!= 0:
return True
else:
return False
year = int(raw_input())
print is_leap(year)
def is_leap(year):
leap = False
# Write your logic here
if year%4==0:
leap= True
if year%100 ==0 and year%400==0:
leap = True
if (year%100 == 0) and (year%400 != 0):
leap = False
return leap
year = int(input())
print(is_leap(year))
def is_leap(year):
leap = False
d4 = year%4
d100 = year%100
d400 = year%400
if d4 == 0 :
if d100 != 0 or d400 == 0 :
leap = True
else :
leap = False
return leap
year = int(input())
print(is_leap(year))

Wait until specific time

I'm writing a program that will do something if now == specific time and day and wait till that time if is not equal.
I have a morning, evening, days values, which shows start time, end time and today's day. I would like to make a program that check if today is a weekday and specific time (between morning and evening) if True to do something and if even one of these is False, gonna wait till that time and after that do something.
I did it with while loop but when it starts with False value(not in right time) it continue printing False even if that time came and value should change to True but it shows True when I start it in right time.
Here is the code:
import datetime
from datetime import date
from time import sleep
#setting values
now = datetime.datetime.now()
morning = now.replace(hour=9, minute=00, second=0, microsecond=0)
evening = now.replace(hour=16, minute=0, second=0, microsecond=0)
days = now.strftime("%A")
#check if time is in range and return True or False
def time_in_range(morning, evening, x):
if morning <= evening:
return morning <= x <= evening
else:
return morning <= x or x <= evening
timerange = time_in_range(morning, evening, now)
#check if today is weekday
if date.today().weekday() == 0:
dayz = True
else:
dayz = False
# If today weekday and time range do something
if dayz == True and timerange == True:
print("Yes")
while dayz == False or timerange == False:
sleep(5)
timerange = time_in_range(morning, evening, now)
print(timerange) #this printing false even if is right time.
# But it shows True when I turn it on in right time
You only initialize your now variable once and never update its value to the current now. You should update the value inside the while loop, for example:
while dayz == False or timerange == False:
sleep(5)
now = datetime.datetime.now()
...
If you are interested in checking just the hours to determine morning and evening as I can see in your code, you can use below snippet:
from datetime import datetime
from datetime import timedelta
from time import sleep
morning_hour = 9
evening_hour = 16
while True:
curr_time = datetime.now()
print("Current time : {0}".format(curr_time))
if curr_time.hour < morning_hour or curr_time.hour > evening_hour or not curr_time.isoweekday():
print("Job start conditions not met. Determining sleep time")
add_days = 0
current_day = curr_time.weekday() == 4
# Add 3 days for fridays to skip Sat/Sun
if current_day == 4:
add_days = 3
# Add 2 days for Saturdays to skip Sunday
elif current_day == 5:
add_days = 2
else:
add_days = 1
next_window = (curr_time + timedelta(days=add_days)).replace(hour=9, minute=0,second=0,microsecond=0)
delta = next_window - datetime.now()
print("Sleep secs : {0}".format(delta.seconds))
sleep(delta.seconds)
else:
print("Do something")
break

Formatting, not printing incorrect format?

Hey I'm having an issue getting the last bit of my code to run.
I am unable to get the values at the end and believe it may have to do with my formatting, although I'm not entirely sure. Instead of stabbing in the dark I thought I'd ask around here as the fastest way to improve is with help from the more experienced.
I'm new, and not seasoned. Haven't been programming for a full 2 months yet.
import math
def month():
month = input(' # of month born ')
if month == '1':
print ("January")
return "January"
elif month == '2':
print ("February")
return "February"
elif month == '3':
print ("March")
return "March"
elif month == '4':
print ("April")
return "April"
elif month == '5':
print ("May")
return "May"
elif month == '6':
print("June")
return ("June")
elif month == '7':
print ("July")
return "July"
elif month == '8':
print("August")
return "August"
elif month == '9':
print("september")
return "September"
elif month == '10':
print("October")
return "October"
elif month == '11':
print ("November")
return "November"
elif month == '12':
return "December"
print ("December")
else:
return month()
month()
print('day born')
day=input(' input day # ')
print ('{}'.format (day))
if month==1 and day<20:
print ('Capricorn')
elif month ==1 and day>22:
print ('aquarius')
It does everything fine except return aquarious or capricorn.
How may I format it correctly so it prints these values?
You run the function month(), right after the definition of it, but you do not store the return value. You should do this:
m = month()
if m == "October":
# ...
But instead, you're comparing the function month to 1, which will result to False.
def month(): pass # month is a function
month == 1 # is month equal to 1? no! this is False
Also, the function month actually returns string by your design, so you should not compare it to 1, but to "January", for example. Also, there's a very handy builtin package for this, you can use datetime here, see https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior.
In [3]: import datetime
In [4]: datetime.datetime(2000, 1, 1).strftime('%B')
Out[4]: 'January'
In [5]: datetime.datetime(2000, 12, 1).strftime('%B')
Out[5]: 'December'
So in a function:
def convert_number_to_month_name(i):
return datetime.datetime(2000, i, 1).strftime('%B')

Categories