Trying to make it so Largest Task is pointed out in the print. Got everything else just need to able to grab the Largest Task.
def main ():
print("*** TIME MANAGEMENT ASSISTANT ***") NumberOfTasks = int(input("Number of tasks: "))
total = 0.0
TotalHour = 0.0
Day = 0.0
Minute = 0.0
EndTimeMinute = 0.0
EndTimeHour = 0.0
EndTimeDay = 0.0
RemainingHour = 0.0
AverageMinutes = 0.0print("What time will you start (on a 24-hour clock)? ")
StartHour = int(input("Hour: "))
StartMinute = int(input("Minute: "))
for i in range (NumberOfTasks):
TaskName = input("Task description: ")
TaskTime = int(input("How many minutes will this task take? "))
total = int(total + TaskTime)
TotalHour = int(total//60)
Minute = int(total%60)
Day = int(TotalHour//24)
RemainingHour = int(TotalHour%24)
EndTimeDay = Day
EndTimeHour = TotalHour + StartHour
if EndTimeHour > 24:
EndTimeHour = int(total%60)
EndTimeMinute = Minute + StartMinute
AverageMinutes = float(total//NumberOfTasks)
print("TOTAL TIME:", Day, "day(s)", RemainingHour, "hour(s)", Minute, "minute(s)")
print("END TIME: ", "In ", EndTimeDay, " day(s) at ", EndTimeHour, ":", EndTimeMinute,sep="")
print("LONGEST TASK: ")
print("AVERAGE TASK LENGTH:", round(AverageMinutes,2), "minutes")
You need to record the time of each "task," and then calculate the longest after the loop by sorting. To implement this way, you need to ensure task names are unique, so I've added a line of code to do that (all additions are commented):
def main():
print("*** TIME MANAGEMENT ASSISTANT ***")
NumberOfTasks = int(input("Number of tasks: "))
total = 0.0
TotalHour = 0.0
Day = 0.0
Minute = 0.0
EndTimeMinute = 0.0
EndTimeHour = 0.0
EndTimeDay = 0.0
RemainingHour = 0.0
AverageMinutes = 0.0
print("What time will you start (on a 24-hour clock)? ")
StartHour = int(input("Hour: "))
StartMinute = int(input("Minute: "))
# create a dictionary to store time for each task
task_times = {}
for i in range (NumberOfTasks):
TaskName = input("Task description: ")
# ensure task name is unique
while TaskName in task_times.keys():
TaskName = input("Task description has already been used. Please enter a unique description: ")
TaskTime = int(input("How many minutes will this task take? "))
total = int(total + TaskTime)
TotalHour = int(total//60)
Minute = int(total%60)
Day = int(TotalHour//24)
RemainingHour = int(TotalHour%24)
EndTimeDay = Day
EndTimeHour = TotalHour + StartHour
if EndTimeHour > 24:
EndTimeHour = int(total%60)
EndTimeMinute = Minute + StartMinute
AverageMinutes = float(total//NumberOfTasks)
# record time for this task in the dictionary
task_times[TaskName] = TaskTime
print("TOTAL TIME:", Day, "day(s)", RemainingHour, "hour(s)", Minute, "minute(s)")
print("END TIME: ", "In ", EndTimeDay, " day(s) at ", EndTimeHour, ":", EndTimeMinute, sep="")
# calculate longest task by sorting by time and taking the last item
longest_task_name, longest_task_length = sorted(task_times.items(), key=lambda x: x[1])[-1]
print("LONGEST TASK: {}".format(longest_task_name))
print("AVERAGE TASK LENGTH:", round(AverageMinutes,2), "minutes")
Related
print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = datetime.time(time1h,time1m,time1s)
time2 = datetime.time(time2h,time2m,time2s)
diff = datetime.timedelta(hours=(time2.hour - time1.hour), minutes=(time2.minute - time1.minute), seconds=(time2.second - time1.second))
print(diff)
I am trying to print the results from the diff variable separately from each other so I can format it like
"You ran for (diffhours) hours, (diffminutes) minutes, and (diffseconds) seconds"
Alternatively you could do something like this
output_string = str(diff).split(':')
print("You ran for {} hours, {} minutes, and {} seconds".format(*output_string))
While you can use diff.seconds and then carry out various calculations to convert it to hours and minutes as suggested in the other answers, it's also possible to convert diff to a string and process it that way:
diff = str(diff).split(':') # diff will be something like 1:01:23
print(f'You ran for {diff[0]} hours, {diff[1]} minutes and {diff[2]} seconds')
Example output:
You ran for 1 hours, 01 minutes and 01 seconds
Here is the code:
print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = timedelta(hours=time1h, minutes=time1m, seconds=time1s)
time2 = timedelta(hours=time2h, minutes=time2m, seconds=time2s)
diff = time2-time1
total_sec = diff.total_seconds()
h = int(total_sec // 3600)
total_sec = total_sec % 3600
m = int(total_sec // 60)
s = int(total_sec % 60)
print(f"You ran for {h} hours, {m} minutes, and {s} seconds")
For a bit of context, the user enters patient number, and 3 body temps, and then those 3 temps are averaged and a diagnosis is given. Problem is I cannot get all of the inputs to be printed and not sure how to fix it.
average = 0
total_patient = 0
total = 0
i = 0
fever = 0
chilled = 0
avg_list = []
PT_list = {}
diagnosis = ('')
print()
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
patient = input('Enter patient: ')
while patient != '':
avg_list = patient.replace(',', ' ')
if patient != ('\n'):
total_patient += 1
total = avg_list.split()
average = (float(total[1]) + float(total[2]) + float(total[3])) / 3
patient = input('Enter patient: ')
PT_list[i] = total[0], average, diagnosis
print()
print('PT AVG Diagnosis')
for num in PT_list:
if average > 98.7:
diagnosis = ('fever')
fever += 1
elif average < 95.0:
diagnosis = ('chilled')
chilled += 1
else:
diagnosis = ('')
print(total[0], ' ', round(average, 2), ' ', diagnosis)
You only need to increment i after this line PT_list[i] = total[0], average, diagnosis. the edited version of code:
average = 0
total_patient = 0
total = 0
i = 0
fever = 0
chilled = 0
avg_list = []
PT_list = {}
diagnosis = ('')
print()
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
patient = input('Enter patient: ')
while patient != '':
avg_list = patient.replace(',', ' ')
if patient != ('\n'):
total_patient += 1
total = avg_list.split()
average = (float(total[1]) + float(total[2]) + float(total[3])) / 3
patient = input('Enter patient: ')
PT_list[i] = total[0], average, diagnosis
i += 1 # <=== check this line
print()
print('PT AVG Diagnosis')
for num in PT_list:
if average > 98.7:
diagnosis = ('fever')
fever += 1
elif average < 95.0:
diagnosis = ('chilled')
chilled += 1
else:
diagnosis = ('')
print(total[0], ' ', round(average, 2), ' ', diagnosis)
total_patient = fever = chilled = 0
PT_list = []
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
while True:
patient = input('Enter patient: ')
if patient == "": break
avg_list = patient.replace(',', ' ')
total_patient += 1
total = avg_list.split()
average = (float(total[1]) + float(total[2]) + float(total[3])) / 3
PT_list.append((total[0], average))
print('PT AVG Diagnosis')
for PT in PT_list:
if PT[1] > 98.7:
diagnosis = 'fever'
fever += 1
elif PT[1] < 95.0:
diagnosis = 'chilled'
chilled += 1
else:
diagnosis = ''
print(PT[0], ' ', round(PT[1], 2), ' ', diagnosis)
Use a list instead of a dict, then you can just append to it instead of having to keep track of (and increment) a key value.
patient_data = []
print()
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
while True:
patient = input('Enter patient: ').replace(",", " ")
if not patient:
break
num, *temps = patient.split()
average = sum(float(t) for t in temps) / len(temps)
patient_data.append((num, average))
print()
print('PT AVG Diagnosis')
for num, average in patient_data:
if average > 98.7:
diagnosis = 'fever'
elif average < 95.0:
diagnosis = 'chilled'
else:
diagnosis = ''
print(f"{num:<10}{average:<10}{diagnosis}")
Enter patient number and three temperature readings
Enter blank line to stop entering data
Enter patient: 123,99,101,100
Enter patient: 234,98,99,99
Enter patient: 345,97,96,95
Enter patient:
PT AVG Diagnosis
123 100.0 fever
234 98.67
345 96.0
This is my code to find the time difference. You input hour and time of your preference. Remaining time is calculated by finding the difference between your input and current time but it is not working for me.
time_hour = input("Enter hour: ")
time_minutes = input("Enter minutes: ")
set_time = time_hour + ":" + time_minutes
print("Set Time: ", set_time)
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Current Time: ", current_time)
dif = set_time - current_time
print(dif)
I am able to get the set time and current time, but not the difference.
This is the output of the program:
Enter hour: 10
Enter minutes: 30
Set Time: 10:30
Current Time: 11:14
You are actually subtracting string from datetime, so convert the first input time to datetime first
time_hour = input("Enter hour: ")
time_minutes = input("Enter minutes: ")
set_time = time_hour + ":" + time_minutes
the_time = datetime.strptime(set_time,'%H:%M')
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Current Time: ", current_time)
dif = the_time - current_time
print(dif)
So I am quite new to python and have been working on this assignment for a week now on and off and can't quite get it to run correctly. I am now getting errors that tell me the function get_in_code is not defined although I've defined it. Any help would be greatly appreciated!
SENTINEL = 'XXX'
DAY_CHARGE = 1500.00
#Define get_days
def get_days():
good_data = False
while not good_data:
try:
n_days = int(input("Please enter the number of days you stayed: "))
except ValueError:
print("Error, Bad Data")
else:
if n_days > 0:
good_data = True
else:
print("This is bad data, please re enter data")
return n_days
#define get_cost(p)
def get_cost():
cost = float(input("Please enter the cost for the procedures: "))
while cost < 0:
print("Procedure cost cant be negative: ")
cost = float(input("Please enter the cost for the procedures: "))
return cost
#define med cost
def med_cost():
med_cost = float(input("Enter the cost of your medicine: "))
while med_cost < 0:
print("Medicine cost cant be negative: ")
med_cost = float(input("Enter the cost of your medicine: "))
return med_cost
#Find day cost
def find_day_cost(in_code, n_days):
day_cost = n_days * DAY_CHARGE
if in_code == 'ZH':
p_day_cost = day_cost * 0.20
in_day_cost = day_cost *0.80
elif in_code == 'HH':
p_day_cost = day_cost * 0.10
in_day_cost = day_cost * 0.90
elif in_code == 'CH':
p_day_cost = day_cost * 0.25
in_day_cost = day_cost * 0.75
else:
p_day_cost = day_cost
in_day_cost = 0
return p_day_cost, in_day_cost
#find procedure cost
def find_proc_cost(in_code, cost):
if in_code == 'ZH':
p_proc_cost = 0
in_proc_cost = cost
elif in_code == 'HH':
p_proc_cost = cost * 0.10
in_proc_cost = cost * 0.90
elif in_code == 'CH':
p_proc_cost = cost * 0.50
in_proc_cost = cost * 0.50
else:
p_proc_cost = cost
in_proc_cost = 0
return p_proc_cost, in_proc_cost
#find medicine cost
def find_med_cost(in_code, med_cost):
if in_code == 'ZH':
p_med_cost = 0
in_med_cost = med_cost
elif in_code == 'HH':
p_med_cost = med_cost * 0.10
in_med_cost = med_cost * 0.90
elif in_code == 'CH':
p_med_cost = med_cost * 0.50
in_med_cost = med_cost * 0.50
else:
p_med_cost = med_cost
in_med_cost = 0
return p_med_cost, in_med_cost
#Display pat_info
def display_pat_info(pat_name, in_name):
print("City Hospital - Patient Invoice")
print("Patient Name: ", pat_name)
print("Insurance: ", in_name)
#display day cost
def display_day_cost(p_day_cost, in_day_cost):
print("Patient Day Cost: ", p_day_cost,"\tInsurance Day Cost: ", in_day_cost)
#display procedure cost
def display_proc_cost(p_proc_cost, in_proc_cost):
print("Patient Procedure Cost: ", p_proc_cost, "\tInsurance Procedure Cost: ", in_proc_cost)
#display medicine cost
def display_med_cost(p_med_cost, in_med_cost):
print("Patient Medicine Cost: ", p_med_cost, "\tInsurce Medicine Cost: ", in_med_cost)
#Display totals
def display_totals(total_pat, total_in):
print("Total Billed To Patient: ", total_pat, "\tTotal Billed To Insurance: ", total_in, "\tTotal Bill: ", (total_pat + total_in))
#display day_totals
def display_day_totals(total_zip, total_happy, total_cheap, total_pat):
print("City Hospital - End Of Day Billing Report")
print("Total Dollar Amount Billed Today: ", total_zip+total_happy+total_cheap+total_pat)
print("Total Billed To Zippy Healthcare: ", total_zip)
print("Total Billed To Happy Healthcare: ", total_happy)
print("Total Billed To Cheap Healthcare: ", total_cheap)
print("Total Billed To Uninsured: ", total_pat)
#display day_counts()
def display_day_counts(zip_count, happy_count, cheap_count, no_in_count):
print("The total amount of Zippy Healthcare patients is: ", zip_count)
print("The total amount of Happy Healthcare patients is: ", happy_count)
print("The total amount of Cheap Healthcare patients is: ", cheap_count)
print("The total amount of Uninsured patients is: ", no_in_count)
#def main
def main():
#Counters and accumulators
total_zip= 0.00
total_cheap= 0.00
total_happy= 0.00
total_pat= 0.00
zip_count= 0
cheap_count= 0
happy_count= 0
no_in_count= 0
total_in = 0
#Open file
try:
Pat_File = open('PatientBill.txt', 'w')
except ValueError:
print("*****ERROR***** - Corrupt File")
else:
file_exist = True
#Priming read
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Processing loop
while pat_name != SENTINEL:
#Input data
in_code = get_in_code()
num_days = get_days()
proc_cost = get_cost()
med_cost = med_cost()
#find each cost
pat_day, insure_day = find_day_cost(in_code, num_days)
pat_proc, insure_proc = find_proc_cost(in_code, proc_cost)
pat_med, insure_med = find_med_cost(in_code, med_cost)
#update accumulators and totals
total_pat += pat_day + pat_proc + pat_med
if in_code == 'ZH':
zip_count += 1
total_zip += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Zippy Healthcare'
elif in_code == 'HH':
happy_count += 1
total_happy += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Happy Healthcare'
elif in_code == 'CH':
cheap_count += 1
total_cheap += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Cheap Healthcare'
else:
no_in_count += 1
in_name = 'Uninsured'
total_in = total_zip + total_happy + total_cheap
#displays patients invoice
display_pat_info(pat_name,in_name)
display_day_cost(pat_day, insure_day)
display_proc_cost(pat_proc, insure_proc)
display_med_cost(pat_med, insure_med)
display_totals(pat_day + pat_proc + pat_med, insure_day + insure_proc + insure_med)
#Write output to file
if file_exist:
Pat_File.write(pat_name, pat_day+pat_med+pat_proc )
#Get next patients name
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Close the output file
if file_exist:
Pat_File.close()
#display the accumlators and totals
display_day_totals(total_zip, total_happy, total_cheap, total_pat)
display_day_counts(zip_count,happy_count,cheap_count,no_in_count)
#define get_in_code
def get_in_code():
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
while in_code not in ('ZH', 'HH', 'CH', 'XX'):
print("***Please enter a proper insurance code***")
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
return in_code
main()
Python is a interpreted language. You need to define function prior to its usage. Just move a function definitions at the top of a file.
The problem is also with indentation. You're defining your methods inside while, just after a return statement. Actual functions aren't defined at all - interpreter doesn't reach those lines.
Besides, the code is "dirty". Split the code into separate classes/modules. Create well defined areas of responsibility, that would improve the code and it'll be easier to work with it.
I have a question about my python program . I have trouble finding the total and ntotal in this program. Rest works fine. Is there any way i can fix this? I have this program due soon. I'd appreciate any tips I can get :D Thanks
midSalary = 50000
maxSalary = 60000
def main():
inFile = open('program7.txt', 'r')
lineRead = inFile.readline()
total = 0.0
ntotal = 0.0
count = 0
while lineRead != '':
words = lineRead.split()
for word in words:
num = float(word)
total += num
count += 1
print("\nFaculty Member # ",count, ": $" , format(num, '.2f'), sep ="")
if num >= maxSalary:
payIncrease(num, .04)
elif num >= midSalary:
payIncrease(num, .07)
else:
payIncrease(num , .055)
lineRead = inFile.readline()
#averagePayRaise = (ntotal - total) / count
inFile.close()
for divider in range(45):
print("-", end ='')
print("\nTotal Faculty payroll : $", format(total , ",.2f"),sep ="")
print("The New Total Faculty payroll : $", format(ntotal , ",.2f"),sep ="")
print("Average Pay Raise : $", format(averagePayRaise, ",.2f"), sep ="")
def payIncrease(amount, prcnt):
print("Pay Raise Percent : ", format(prcnt*100, ".1f")+"%")
total = 0.0
ntotal = 0.0
count = 0
salRaise = amount * prcnt
newSal = amount + salRaise
print("Pay Raise : $", format(salRaise, ',.2f'), sep ="")
print("New Salary : $", format(newSal, ',.2f'), sep = "")
total += amount
count += 1
ntotal += newSal
averagePayRaise = (ntotal - total) / count
main()
By default, names that you assign to in Python are local to the function in which they are declared. So, if you have:
def main():
total = 0
def payIncrease():
total = 0
total += amount
then you have two independent values named total. One way to solve this is to make it global:
total = 0
def main():
global total
total = 0
def payIncrease():
global total
total += amount
Note that you don't want to assign total = 0 inside payIncrease(), because that would reset your running total to 0. You probably added that when you broke out your code into the payIncrease() function because Python gave you an error without that.
def payIncrease(salary):
if current_sal >= maxSalary: return 0.04
if current_sal >= midSalary: return 0.07
return 0.055
def processSalaryData(line):
"""take a line and return current salary and new salary (note that a line is actually just a float)"""
try:
current_sal = float(line)
except ValueError:
return None
return current_sal,current_sal + current_sal*payIncrease(current_sal)
def main():
salaryData = [processSalaryData(line) for line in open("salaries.txt")]
salaryData = filter(None,salaryData) #filter out invalid data
adjustments = [b-a for a,b in salaryData]
old_salaries,new_salaries = zip(*salaryData)
print "OLD TOTAL PAYROLL :",sum(old_salaries)
print "NEW TOTAL PAYROLL :",sum(new_salaries)
print "AVG ADJUSTMENT:",sum(adjustments)/len(adjustments)
print "MAX SALARY:",max(new_salaries)
print "MIN SALARY:",min(new_salaries)