Question

In: Computer Science

Python: I am not sure where to begin with this question, and I hope I can...

Python: I am not sure where to begin with this question, and I hope I can get an input on it. This is in regards to Downey's program, and we are asked to make two changes.

  • Downey prints time as they do in the Army: 17:30:00 hours. We want to print that as 5:30 PM.
  • Downey lets you define the time 25:00:00 - we want to turn over at 23:59:59 to 00:00:00.

(I am asked to identify my changes with #)

A) Rewrite the dunder str method used to print the time. It currently prints Time(17, 30, 0) as

    17:30:00

Modify it to return

    5:30 PM

Hours are numbers between 1 and 12 inclusive, seconds are suppressed, and times end with AM or PM. For purposes of this problem, midnight is AM, while noon is PM.

B) Time2.py currently allows you to create times with hours greater than 23. Identify the routines that Downey provides that would have to change to keep hours less than 24.

C) Make the changes required to keep hours less than 24.

D) Include the tests you have used to verify your changes.

Run the unit tests: all times should be within 24 hours

Here's the code below:

""
  
Code example from Think Python, by Allen B. Downey.
Available from http://thinkpython.com

Copyright 2012 Allen B. Downey.
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.

"""

class Time(object):
"""Represents the time of day.

attributes: hour, minute, second
"""
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second

# Modify this routine
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

def print_time(self):
print(str(self))

def time_to_int(self):
"""Computes the number of seconds since midnight."""
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds

def is_after(self, other):
"""Returns True if t1 is after t2; false otherwise."""
return self.time_to_int() > other.time_to_int()

def __add__(self, other):
"""Adds two Time objects or a Time object and a number.

other: Time object or number of seconds
"""
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)

def __radd__(self, other):
"""Adds two Time objects or a Time object and a number."""
return self.__add__(other)

def add_time(self, other):
"""Adds two time objects."""
assert self.is_valid() and other.is_valid()
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)

def increment(self, seconds):
"""Returns a new Time that is the sum of this time and seconds."""
seconds += self.time_to_int()
return int_to_time(seconds)

def is_valid(self):
"""Checks whether a Time object satisfies the invariants."""
if self.hour < 0 or self.minute < 0 or self.second < 0:
return False
if self.minute >= 60 or self.second >= 60:
return False
return True


def int_to_time(seconds):
"""Makes a new Time object.

seconds: int seconds since midnight.
"""
minutes, second = divmod(seconds, 60)
hour, minute = divmod(minutes, 60)
time = Time(hour, minute, second)
return time

# TESTING features of Class Time
def main():
start = Time(9, 45, 00)
start.print_time()

end = start.increment(1337)
end.print_time()

print('Is end after start?', end=" ")
print(end.is_after(start))

# Testing __str__
print(f'Using __str__: {start} {end}')

# Testing addition
start = Time(9, 45)
duration = Time(1, 35)
print(start + duration)
print(start + 1337)
print(1337 + start)

print('Example of polymorphism')
t1 = Time(7, 43)
t2 = Time(7, 41)
t3 = Time(7, 37)
total = sum([t1, t2, t3])
print(total)

# A time that is invalid
t1 = Time(50)
print(t1)

Solutions

Expert Solution

def convert24To12(str): 
    sss=str[6]+str[7]               #get seconds
    se = (int)(sss)                 #convert seconds to integer
    
    h1 = ord(str[0]) - ord('0')     #get first string 
    h2 = ord(str[1]) - ord('0')    #get second string 
  
    hour = h1 * 10 + h2           #for example 12:55:43 here h1=1, h2=2,hour=1*10+2=>12
   
    meridien=""; 
    if (((int)(hour/12))%2 == 0):          # find the meridien i.e AM or PM
        meridien = "AM"
    else: 
        meridien = "PM"
  
    if (hour == 0):                     #handle if hour is 00
        print("00", end = "")         # it will print hour
        if se!=0:
            for i in range(2, 6):            #It will Print minutes
                print(str[i], end = "")
            print(sss,end="")                #it will print seconds
        else:
             for i in range(2, 5):           #It will Print minutes if second is 00
                 print(str[i], end = "")
                 
    elif hour==12:                          #handle if hour is 12
        print("12",end = "")                # it will print hour
        if se!=0:
            for i in range(2, 6):            #It will Print minutes
                print(str[i], end = "")
            print(sss,end="")               #it will print seconds
        else:
            for i in range(2, 5):            #It will Print minutes if seconds is 00
                print(str[i], end = "")
                
    else:                               #handle if hour is not 00 or 12
        hour %= 12;                     #convert hour from 24 to 12 hour formate
        if hour<10:
            print("0",end = "")         
        print(hour,end="")              # it will print hour            
        if se!=0:
            for i in range(2, 6):            #It will Print minutes
                print(str[i], end = "")
            print(sss,end="")               #it will print seconds
        else:
             for i in range(2, 5):           #It will Print minutes if second is 00
                 print(str[i], end = "")
  
    print(" " + meridien);              #after time print meridien
  
if __name__ == '__main__':              # Driver code 

    str = input("Enter time in hh:mm:ss formate: ")    #input
    convert24To12(str);                                 #calling the function

Related Solutions

I am not sure where, to begin with, this problem... "You have found the following historical...
I am not sure where, to begin with, this problem... "You have found the following historical information for DEF Company:                          Year1       Year 2        Year 3        Year 4 Stock Price        $46.29         $49.74          $54.55          $57.07 EPS                  $2.04 $2.9    $2.81    $3.78 Earnings are expected to grow at 8 percent for the next year. Using the company's historical average PE as a benchmark, what is the target stock price in one year?"
The Table in my homework question below is completely wrong. I am not sure where I...
The Table in my homework question below is completely wrong. I am not sure where I went wrong in my calculations but coud you rework this question and answer the parts below?? Here are earnings per share for two companies by quarter from the first quarter of 2009 through the second quarter of 2012. Forecast earnings per share for the rest of 2012 and 2013. Use exponential smoothing to forecast the third period of 2012, and the time series decomposition...
I am sure this is a silly question, but I was reading something that described the...
I am sure this is a silly question, but I was reading something that described the pre big-bang universe as having "nearly infinite mass." How can something be "nearly" infinite? The term seems to make no sense.
I have a concept question that I am not sure how to answer: ABC Company is...
I have a concept question that I am not sure how to answer: ABC Company is in the process of preparing a budget for the upcoming year. The marketing department has just increased the number of units in the sales budget by a significant 50% as compared to the last sales budget that was prepared for the year. Explain the impact this change will have on the Cash Budget. Be specific about… how the components of the Cash Budget will...
I am stuck on this problem and I am not sure what the solution is. In...
I am stuck on this problem and I am not sure what the solution is. In C Write item.h and item.c. In item.h, typedef a struct (of type t_item) which contains the following information: t_item: char name[MAX_ITEM_NAME_STRING]; char description[MAX_ITEM_DESCRIPTION_STRING]; Make sure that MAX_ITEM_NAME_STRING and MAX_ITEM_DESCRIPTION_STRING are defined with suitable sizes in your item.h. Typical values are, 25 and 80, respectively. Add the following interface definition to item.h: int item_load_items(t_item items[], int max_items, char *filename); Returns the number of objects loaded...
I am trying to determine the weight of long-term debt but don't know where to begin....
I am trying to determine the weight of long-term debt but don't know where to begin. I know the answer is 22.58% but I don't know how to get there.   This is the problem: Problem 9-17 WACC Estimation The following table gives the balance sheet for Travellers Inn Inc. (TII), a company that was formed by merging a number of regional motel chains. Travellers Inn: (Millions of Dollars) Cash $10 Accounts payable $10 Accounts receivable 20 Accruals 10 Inventories 20...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
I am not quite sure what this question is asking, nor do I understand how to...
I am not quite sure what this question is asking, nor do I understand how to apply the lower-of-cost-or-NRV. The controller of Alt Company is applying the lower-of-cost-or-net realizable value basis of valuing its ending inventory. The following information is available: Cost Net Realizable Value Lawnmowers: Self-propelled $14,800 $17,000 Push type 19,000 18,000 Total 33,800 35,000 Snowblowers: Manual 29,800 31,000 Self-start 19,000 21,000 Total 48,800 52,000 Total inventory $82,600 $87,000 Compute the value of the ending inventory by applying the...
The question below is very long and I am not sure how to answer some of...
The question below is very long and I am not sure how to answer some of the questions. How much energy is needed for normal breathing? and How might this change with lung disease? how the ingredients in tobacco smoke damage/impair the respiratory system? What brain region controls respiration? What gas do the respiratory centers of the brain detect? How does this affect the respiration rate??
I am working on this problem for the company AT & T and am not sure...
I am working on this problem for the company AT & T and am not sure how to start it. Draw a chart of the main inter-organizational linkage mechanisms (e.g., long -term contacts, strategic alliances, mergers) that your organization uses to manage its symbiotic resource interdependencies. Using resource dependence theory and transaction cost theory, discuss why the organization to manage its interdependencies in this way. Do you think the organization has selected the most appropriate linkage mechanisms? Why or why...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT