Last active
March 10, 2021 21:06
-
-
Save hovissimo/ba65ea89315aa3c6189a1f50e671d627 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Truck: | |
def __init__(self, num_wheels, max_load_per_wheel): | |
self.num_wheels = num_wheels | |
self.max_load_per_wheel = max_load_per_wheel | |
self.cargo = [] | |
def max_load(self): | |
return self.max_load_per_wheel * self.num_wheels | |
def describe_cargo(self): | |
if len(self.cargo) == 1: | |
# Special case for pluralization | |
print("There is 1 item in our cargo.") | |
else: | |
print(f"There are {len(self.cargo)} items in our cargo.") | |
for item in self.cargo: | |
print(f"The {item[0]} weighs {item[1]} kg.") | |
print(f"The total cargo weight is {self.cargo_mass()} kg. We have room for {self.max_load() - self.cargo_mass()} kg more.") | |
print() # Extra newline keeps output tidy | |
# def dump_cargo(self, cargo_name): | |
# self.cargo = [item for item in self.cargo if item[0] != cargo_name] | |
def dump_cargo(self, cargo_name): | |
# Iterate over self.cargo in reverse order so that deleting elements doesn't shift our index | |
for i in range(len(self.cargo))[::-1]: | |
if self.cargo[i][0] == cargo_name: | |
del self.cargo[i] | |
def cargo_mass(self): | |
return sum([thing[1] for thing in self.cargo]) | |
def add_cargo(self, cargo_name, cargo_mass): | |
if cargo_mass + self.cargo_mass() > self.max_load(): | |
print("Stop! That's too heavy!\n") | |
else: | |
self.cargo.append((cargo_name, cargo_mass)) | |
print("Big truck") | |
big_truck = Truck(6, 300) | |
big_truck.describe_cargo() | |
big_truck.add_cargo("crate of coconuts", 300) | |
big_truck.add_cargo("crate of bananas", 450) | |
big_truck.describe_cargo() | |
big_truck.dump_cargo("crate of coconuts") | |
big_truck.dump_cargo("crate of bananas") | |
big_truck.add_cargo("iron bed", 1200) | |
big_truck.describe_cargo() | |
big_truck.add_cargo("elephant", 6000) | |
print("Little truck") | |
little_truck = Truck(4, 150) | |
little_truck.add_cargo("crate of coconuts", 300) | |
little_truck.describe_cargo() | |
little_truck.add_cargo("crate of bananas", 450) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment