Practice Problem
Instructions
Writing class, methods, and functions
- Write a
PlaneTicketclass with attributes:departure_city: str,arrival_city: str,departure_time: int,ticket_cost: float. - Write an
__init__magic method that takescity_a: str,city_b: str,depart: int, andcost: floatas arguments as creates a newPlaneTicketwith the attributesdeparture_city = city_a,arrival_city = city_b,departure_time = depart, andticket_cost = cost. - Write a
__str__magic method to print out ticket info. (Format however you want.) - Write a
delaymethod that takesdelay_hours: intas an argument and increases thedeparture_timeby that much. (Think of time like military time… 1 am is0100, 1 pm is1300, etc.) - Write a
discountmethod that takes adiscount: floatas an argument and discountsticket_costby that percent. (E.g. ifdiscount = .15, then discountticket_costby 15%) - Write a
find_cheapest_ticketfunction that takes as input a list ofPlaneTickets and returns thePlaneTicketwith the lowest cost.
Writing code to instantiate class and test methods and functions
- Create a
PlaneTicketobject that starts in “Raleigh” and ends in “New Orleans”. It departs at 10 am (1000) and costs $85.25. - Print out the ticket info.
- Delay the flight by 2 hours.
- Discount it by 10%.
- Create another
PlaneTicketobject that starts in “Orlando” and ends in “San Fransisco”. It departs at 11 am (1100) and costs $100.50. - Print out the which ticket is cheaper using the
find_cheapest_ticketfunction.
Solution
class PlaneTicket:
departure_city: str
arrival_city: str
departure_time: int
ticket_cost: float
def __init__(self, city_a: str, city_b: str, depart: int, cost: float):
"""Initialize PlaneTicket Class"""
self.departure_city = city_a
self.arrival_city = city_b
self.departure_time = depart
self.ticket_cost = cost
def __str__(self) -> str:
"""Visualize my ticket"""
my_ticket_str: str = f"Depart from {self.departure_city} at {self.departure_time}. "
my_ticket_str += f"Arrive at {self.arrival_city}. It costs ${round(self.ticket_cost, 2)}."
return my_ticket_str
def delay(self, delay_hours: int) -> None:
"""Delay departure_time by delay_hours"""
self.departure_time += (delay_hours * 100)
self.departure_time %= 2400
def discount(self, discount: float) -> None:
"""Discount ticket_cost by 'discount'"""
#If discounting by .15, then multiply by (1-.15)
self.ticket_cost = self.ticket_cost * (1 - discount)
def find_cheapest_ticket(tickets: list[PlaneTicket]) -> PlaneTicket:
min_ticket: PlaneTicket = tickets[0]
for t in tickets:
if t.ticket_cost < min_ticket.ticket_cost:
min_ticket = t
return min_ticket
my_ticket: PlaneTicket = PlaneTicket("Raleigh", "New Orleans", 1000, 85.25)
print(my_ticket)
my_ticket.delay(2)
my_ticket.discount(.10)
other_ticket: PlaneTicket = PlaneTicket("Orlando", "San Fransisco", 1100, 100.50)
print(find_cheapest_ticket([my_ticket, other_ticket]))