find an overlapping apppointment in a list - python

After it validates the date and time for the appointment I need to make sure it doesn't overlap with a pre-existing appointment in the appontmentList[] and I'm stuck as to where to start.
I'm thinking somewhere along the lines of:
for x in appointmentList:
if start <= x:
print('invalid, overlapping appointment! ')
else:
break
See my full code below:
appointmentList = []
def add_sort():
choice = input ('Add item to diary (a) or sort (s)')
if choice == 's':
print ('sorting')
sortRecords()
elif choice == 'a':
print ('adding')
add_record()
else:
add_sort()
def add_record():
while True:
Priority = input ('What is the priority of your appointment? ')
if 'low' != Priority != 'Low' and 'high' != Priority != 'High':
print('invalid, must be low or high! ')
else:
break
# is_valid_date():
while True:
dt = input('enter date of appointment in dd/mm/yyyy format. ')
day_string, month_string, year_string = dt.split('/')
day = int(day_string)
month = int(month_string)
year = int(year_string)
if month in [1, 3, 5, 7, 8, 10, 12]:
max_days=31
elif month in [4, 6, 9 ,11]:
max_days=30
elif year%4==0 and year%100!=0 or year%400==0:
max_days=29
else:
max_days=28
if month<1 or month>12:
print('invalid, enter a number between 1 - 12')
elif day<1 or day>max_days:
print('invalid, check day')
elif 10000 > year <2022:
print('invalid, enter a year greater than 2021')
# is_valid_time():
Start = int(input('What is the starting time of your appointment? '))
if Start < 7 or Start > 22:
print('invalid, enter a time between 7 - 22. ')
End = int(input('What is the ending time of your appointment? '))
if End < Start or End > 22:
print('invalid, please choose a time after starting time. ')
# def is_concurrent():
from datetime import datetime
start = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(Start), '%H').time())
end = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(End), '%H').time())
current = datetime.now()
if start < current:
print('invalid, enter a time & date in the future! ')
elif end < start:
print('invalid, enter an end time after the start time! ')
else:
break
Subject = input ('What is the subject of your appointment?')
appointment = ['{}; {}; {}; {}; {};'.format(Priority, dt, Start, End, Subject)]
appointmentList.append(appointment)
print(appointmentList)
add_sort()
def sortRecords():
choice = input ('Do you want to sort by priority or time or END. ')
if choice.lower() == 'priority':
print ('priority')
print(appointmentList)
plist = sorted(appointmentList, key = lambda x: x[0])
print(plist)
sortRecords()
elif choice.lower() == 'time':
print('time')
print(appointmentList)
tlist = sorted(appointmentList, key = lambda x: x[1])
print(tlist)
sortRecords()
elif choice.lower() != 'end':
print ('invalid')
sortRecords()
add_sort()
for x in appointmentList:
print (x)
add_sort()
the idea is the user inputs an appointment with priority, date, start time, end time and subject, it first prints like this '[['high; 15/7/2022; 8; 9; Hello;']]' and then saves it to the appointment list, I need to find out how to see if a previously made appointment overlaps with the appointment the user is currently trying to enter.

Related

I get a spare output out of nowhere

My code right here emits a strange output, it gives me the second part of inp_a even though I didn`t ask for it. couldn't find the reason why.
Thanks in advance for the help
inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?\nThe day must be one of the weekdays ")
inp_a = inp_a.split(":")
inp_b = inp_b.split(":")
day = day.lower()
if military_time == "AM":
inp_a[0] = inp_a[0]
elif military_time == "PM":
inp_a[0] = int(inp_a[0]) + 12
inp_a[0] = str(inp_a[0])
try:
convert_a1 = int(inp_a[0])
convert_a2 = int(inp_a[1])
convert_b1 = int(inp_b[0])
convert_b2 = int(inp_b[1])
except:
print("-"*50)
print("One of the inputs is incorrect, try again")
while True:
if day == "sunday":
break
elif day == "monday":
break
elif day == "tuesday":
break
elif day == "wednsday":
break
elif day == "thursday":
break
elif day == "friday":
break
elif day == "saturday":
break
else:
print(day,"is not one of the weekdays try again")
quit()
rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))
result = rl_time + time2add
hh = result // 60
mm = result % hh
The error is in this part of the code:
rl_time = int(inp_a[0])*60 + int(input(inp_a[1]))
time2add = int(inp_b[0]*60) + int(input(inp_b[1]))
You're calling input again for no reason, and input prompts the user with its argument (in this case inp_a[1], which is the extra output you're seeing). If you enter something it'll do the same thing on the next line with inp_b[1].
Here's a fixed version of the full thing -- you can simplify a lot by just doing the int conversion once, rather than converting to int, converting back to str, back to int, etc. You also had your while loop in the wrong spot if the intent is to re-prompt the user for new values when something is incorrect.
while True:
inp_a = input("What`s the time you want to start from? ")
military_time = input("is it AM or PM: ").upper()
inp_b = input("How long would you like to wait? ")
day = input("What`s the day today?\n"
"The day must be one of the weekdays"
).lower()
try:
ah, am = map(int, inp_a.split(":"))
bh, bm = map(int, inp_b.split(":"))
except (TypeError, ValueError):
print("Time must be entered as HH:MM")
continue
if day not in ("monday", "tuesday", "wednesday", "thursday", "friday"):
print(f"{day.title()} is not one of the weekdays, try again.")
continue
break
if military_time == "PM":
ah += 12
rl_time = ah * 60 + am
time2add = bh * 60 + bm
result = rl_time + time2add
hh, mm = divmod(result, 60)

How can i convert the input into a Range with interval?

I would like to convert the input into a range with interval. Can anyone please help me.
Ask the user what will be the input of the user either in Celsius or Fahrenheit. If the input is invalid, print invalid and ask to try again.
Ask the user to input the start, range, and interval separated by an asterisk. For example 0*10*2. This means that the start of the conversion will be from 0 to 10 with an interval of 2, thus the value to be converted will be 0, 3, 6, 9
If the start<end, then the interval should be 0<interval otherwise, your program will display an error and ask to try again for #2. Or
If the start>end, then the interval should be 0>interval otherwise, your program will display an error and ask to try again for #2.
If the user inputs only one value, like 10. This means that the start is equal to 1 which will be the default value for start, up to 10, and the interval is 2 which will be the default value of the interval if start<end.
If the user input has two values like 10*2, this means that the start is equal to 10 up to 2. The interval is set to the default value which is equal to -2 since start>end.
ask = input("What would you like to choose? Celcius = 1, Fahrenheit = 2. \nPick option 1 or 2: ")
asks = float(ask)
if asks == 1:
rng = input("Enter the start, range, interval. \n example 0*10*2:").split("*")
rng = range(rng)
print(rng)
answer1_flag = 0
while answer1_flag == 0:
ask = input("What would you like to choose? Celcius = 1, Fahrenheit = 2. \nPick option 1 or 2: ").strip()
if ask == '1' or ask=='2':
answer1_flag = 1
answer2_flag = 0
while answer2_flag==0:
rng = input("Enter the start, range, interval. \n example 0*10*2:").strip()
count = rng.count('*')
if count==0:
start = 1
end = int(rng)
interval = 2
elif count==1:
start,end = map(int,rng.split("*"))
if start<end:
interval = 2
elif start>end:
interval = -2
elif count==2:
start,end,interval = map(int,rng.split("*"))
if start>end and interval>0:
print('Error! If start>end then interval should be a negative number! Please enter the input again.')
elif start<end and interval<0:
print('Error! If start<end then interval should be a positive number! Please enter the input again.')
else:
rng = range(start,end,interval)
answer2_flag = 1
else:
print('Invalid! Try again.')
print(rng)
import sys
def get_celsisu_or_fahrenheit():
print("What would you like to choose: \n1. Celsius\n2. Fahrenheit\n")
cf = input("Enter (1/2): ")
if cf not in ["1", "2"]:
err()
get_celsisu_or_fahrenheit()
return cf
def get_value(is_celsuis):
values = input(f"Enter the value in {'Celsius' if is_celsuis else 'Fahrenheit'}: ").split("*")
values = list(map(lambda x: int(x), values))
start, end, interval = assign_values(values)
# conditions
if start < end and not 0 < interval:
err() and sys.exit(0)
if start > end and not 0 > interval:
err() and sys.exit(0)
return start, end, interval
def assign_values(val):
start, end, interval = 1, None, None
if len(val) == 1:
end = val[0]
elif len(val) == 2:
start, end = val
elif len(val) == 3:
start, end, interval = val
else:
err()
get_value()
if interval is None:
interval = -2 if start > end else 2
return start, end, interval
def err():
print("ERROR: Please check your input and try again.")
print("----------------------------------------------")
def convert(grade, is_celsuis):
return (grade * 9 / 5) + 32 if is_celsuis else (grade - 32) * 5 / 9
def start():
is_celsuis = True if get_celsisu_or_fahrenheit() == "1" else False
start, end, interval = get_value(is_celsuis)
rng = range(start, end, interval)
print(rng)
for x in rng:
is_celsuis and print(f"{x} Celsuis == {round(convert(x, is_celsuis), 2)} Fahrenheit")
not is_celsuis and print(f"{x} Fahrenheit == {round(convert(x, is_celsuis), 2)} Celsuis")
start()

Incorrect code is being called in 'if/elif/else' statement

I'm making an interest calculator that does compound and simple interest. However, the if statement always runs the simple interest script regardless of input.
I have tried changing variables to strings, integers, and floats. I have tried changing variable names, I have tried removing the first block of code entirely. What the heck is wrong with it???
start = input("simple or compound: ")
if start == "simple" or "Simple":
a = float(input('Starting balance: '))
b = float(input('Rate: '))
c = int(input('Years: '))
final = int(a+((a*b*c)/100))
print(final)
elif start == "compound" or "Compound":
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final2 = int(d*(1+(e/100))**f)
print(final2)
else:
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final3 = int(d*(1+(e/100))**f)
print(final3)
If I input Starting balance as 5000, rate as 5, and years as six into simple it gives 6500. But the same result occurs when I call compound.
This expression is not correct:
start == "simple" or "Simple"
should be
start == "simple" or start "Simple"
code below worked:
start = input("simple or compound: ")
if start == "simple" or start == "Simple":
# print("simple")
a = float(input('Starting balance: '))
b = float(input('Rate: '))
c = int(input('Years: '))
final = int(a+((a*b*c)/100))
print(final)
elif start == "compound" or start == "Compound":
# print("compound")
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final2 = int(d*(1+(e/100))**f)
print(final2)
else:
# print("unknown")
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final3 = int(d*(1+(e/100))**f)
print(final3)
Because of operator precedence
if start == "simple" or "Simple"
is evaluated as
if (start == "simple") or "Simple"
The (...) part is True if the user entered "simple", but the "Simple" part is always True.

datetime format over 24 hours

I'm trying to add time and have the output as hh:mm:ss, but when datetime gets over 24 hours it becomes x Days, hh:mm:ss. Is there anyway to only have hh:mm:ss greater than 24 hours?
import datetime
from datetime import timedelta
# intro
print("Welcome to TimeCalc")
print("Calculating Durations")
clear = True
while clear == True:
# first input
firstNumber = True
while firstNumber == True:
time_1 = input("Please enter a time [hh:mm:ss] including 0s: ")
if len(time_1) > 0 and len(time_1) >= 8 and time_1[-6] == ":" and time_1[-3] == ":" and int(time_1[-5:-3]) < 60 and int(time_1[-2:]) < 60:
hours_1 = time_1[:-6]
minutes_1 = time_1[-5:-3]
seconds_1 = time_1[-2:]
hours_1 = int(hours_1)
minutes_1 = int(minutes_1)
seconds_1 = int(seconds_1)
firstNumber = False
else:
print("Invalid Syntax")
time_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)
cont = True
while cont == True:
# second input
secondNumber = True
while secondNumber == True:
time_2 = input("Please enter a time to add [hh:mm:ss] including 0s: ")
if len(time_2) > 0 and len(time_2) >= 8 and time_2[-6] == ":" and time_2[-3] == ":" and int(time_2[-5:-3]) < 60 and int(time_2[-2:]) < 60:
hours_2 = time_2[:-6]
minutes_2 = time_2[-5:-3]
seconds_2 = time_2[-2:]
hours_2 = int(hours_2)
minutes_2 = int(minutes_2)
seconds_2 = int(seconds_2)
secondNumber = False
else:
print("Invalid Syntax")
time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)
total = time_1 + time_2
print("The total duration is: " + str(total))
# continue, clear, or exit
choice = input("Continue: Y | Clear: N | Exit: X: ")
if choice == "Y" or choice == "y":
time_1 = total
elif choice == "N" or choice == "n":
cont = False
elif choice == "X" or choice == "x":
quit()
after total variable, can you try to put this code, maybe this is not a super solution but it works
seconds = int(total.total_seconds())
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("The total duration is: {h:02d}:{m:02d}:{s:02d}".format(h=hours,
m=minutes, s=seconds))
Use the .strftime() method to format your datetime string.
For example,
>>> import datetime
>>> d = datetime.delta(hours=1)
>>> dt = datetime.datetime(2017,10,30,23,10,10) + d
>>> dt.strftime("%H:%M:%S")
'00:10:10'
Hope it help.

Checking the format/contents of a string

This program is intended to ask for the date as dd/mm/yyyy. It should then check to see if the user inputted the date in the correct format (dd/mm/yyyy). My program is not able to recognize the format correctly. This is my program:
date = (input("enter the date as dd/mm/yyyy: "))
date = day, month, year = date.split("/")
if date == (day + '/' + month + '/' + year):
print (date)
if len(day) == 1 or len(day) == 2:
print("1")
if len(month) == 1 or len(month) == 2:
print("2")
if len(year) == 4:
print ("3")
else:
if len(day) == 1 or len(day) == 2:
print("4")
if len(month) == 1 or len(month) == 2:
print("5")
if len(year) == 4:
print ("6")
The numbers being printed currently have no other purpose than to just check the validity of the date. So far, only 4,5, and 6 are being printed, meaning my program is not recognizing the formatting of the date.
Your solution doesn't work because date=day, month, year = date.split("/") sets date to a list, then you're comparing it to a string (day + '/' + month + '/' + year). However, your solution is a solved problem, do instead:
import datetime
date = (input("enter the date as dd/mm/yyyy: "))
try: datetime.datetime.strptime(date,"%d/%m/%Y")
except ValueError: # incorrect format
In addition, you probably are turning this into a datetime object later on anyway, so you can do so in the try block!
As a further optimization, be aware that many users won't WANT to enter their dates using / as a datesep! Do some introspection on your input, and adjust your datesep appropriately.
date = input("enter the date: ")
if "-" in date: datesep = "-"
elif "/" in date: datesep = "/"
elif "." in date: datesep = "."
else: datesep = ""
if len(date) < 6: yeartype = "%y"
elif date[-4:-2] not in ("19","20"): yeartype = "%y"
else: yeartype = "%Y"
try: date = datetime.datetime.strptime(date,"%d{0}%m{0}{1}".format(datesep,yeartype))
except ValueError: # invalid date
Now your code will end up with a valid datetime object of Feb 2nd 2014 for:
02022014
222014
0222014
222014
020214
02214
2214
02-02-2014
02/02/2014
2-2-14
2/2/2014
2/2/14
etc etc etc
You can use the datetime module:
import datetime
def checkdate(date):
try:
datelist = date.split('/')
datetime.datetime(year=int(datelist[2]), month=int(datelist[1]),day=int(datelist[0]))
return True
except:
return False

Categories

Resources