mirror of
https://github.com/DavidGailleton/42-Piscine_Python.git
synced 2026-03-13 20:56:54 +01:00
Compare commits
6 Commits
4a538a844d
...
acc6d274c2
| Author | SHA1 | Date | |
|---|---|---|---|
| acc6d274c2 | |||
| 6c5ddeebf0 | |||
| 096abbde2b | |||
| 1e1e447c25 | |||
| 29c20da5b3 | |||
|
|
33e4e6ed3d |
@@ -5,7 +5,7 @@ if __name__ == "__main__":
|
||||
|
||||
print("=== Welcome to My Garden ===")
|
||||
print("Plant:", name)
|
||||
print("Height:", height, "cm")
|
||||
print("Height: ", height, "cm", sep="")
|
||||
print("Age:", age, "days")
|
||||
print("")
|
||||
print("=== End of Program ===")
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
class Plants:
|
||||
class Plant:
|
||||
name: str
|
||||
height: int
|
||||
age: int
|
||||
days: int
|
||||
|
||||
def __init__(self, name, height, age):
|
||||
def __init__(self, name: str, height: int, days: int) -> None:
|
||||
"""Init plant with his value"""
|
||||
self.name = name
|
||||
self.height = height
|
||||
self.age = age
|
||||
self.days = days
|
||||
|
||||
def print_plant(self):
|
||||
print(self.name.capitalize() + ":", self.height, end="")
|
||||
print("cm,", self.age, "days old")
|
||||
def print_plant(self) -> None:
|
||||
"""Display plant informations"""
|
||||
print(self.name, ": ", self.height,
|
||||
"cm, ", self.days, " days old", sep="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
x = Plants("rose", 25, 30)
|
||||
y = Plants("sunflower", 80, 45)
|
||||
z = Plants("cactus", 15, 120)
|
||||
x = Plant("rose", 25, 30)
|
||||
y = Plant("sunflower", 80, 45)
|
||||
z = Plant("cactus", 15, 120)
|
||||
print("=== Garden Plant Registry ===")
|
||||
x.print_plant()
|
||||
y.print_plant()
|
||||
|
||||
@@ -1,30 +1,37 @@
|
||||
class Plants:
|
||||
name: str
|
||||
height: int
|
||||
p_age: int
|
||||
days: int
|
||||
|
||||
def __init__(self, name, height, age):
|
||||
def __init__(self, name: str, height: int, days: int) -> None:
|
||||
"""Init plant with his value"""
|
||||
self.name = name
|
||||
self.height = height
|
||||
self.p_age = age
|
||||
self.days = days
|
||||
|
||||
def get_info(self):
|
||||
print(self.name.capitalize() + ":", self.height, end="")
|
||||
print("cm,", self.p_age, "days old")
|
||||
def get_info(self) -> None:
|
||||
"""Display plant informations"""
|
||||
print(self.name, ": ", self.height,
|
||||
"cm, ", self.days, " days old", sep="")
|
||||
|
||||
def grow(self):
|
||||
def grow(self) -> None:
|
||||
"""Increase height"""
|
||||
self.height = self.height + 1
|
||||
|
||||
def age(self):
|
||||
self.p_age = self.p_age + 1
|
||||
def age(self) -> None:
|
||||
"""Increase days by one and grow plant"""
|
||||
self.days = self.days + 1
|
||||
self.grow()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
x = Plants("rose", 25, 1)
|
||||
x = Plants("rose", 25, 30)
|
||||
start = x.days
|
||||
print("=== Day 1 ===")
|
||||
x.get_info()
|
||||
i = 1
|
||||
while i < 8:
|
||||
for n in range(1, 7):
|
||||
x.age()
|
||||
i = i + 1
|
||||
print(f"=== Day {x.days - start + 1} ===")
|
||||
x.get_info()
|
||||
print("Growth this week: +",
|
||||
x.days - start, "cm", sep="")
|
||||
|
||||
@@ -1,36 +1,56 @@
|
||||
class Plants:
|
||||
class Plant:
|
||||
name: str
|
||||
height: int
|
||||
p_age: int
|
||||
days: int
|
||||
|
||||
def __init__(self, name, height, age):
|
||||
self.name = name
|
||||
self.height = height
|
||||
self.p_age = age
|
||||
def get_info(self) -> None:
|
||||
"""Display plant informations"""
|
||||
print(self.name, " (", self.height,
|
||||
"cm, ", self.days, " days)", sep="")
|
||||
|
||||
def get_info(self):
|
||||
print(self.name.capitalize() + ":", self.height, end="")
|
||||
print("cm,", self.p_age, "days old")
|
||||
|
||||
def grow(self):
|
||||
def grow(self) -> None:
|
||||
"""Increase height"""
|
||||
self.height = self.height + 1
|
||||
|
||||
def age(self):
|
||||
self.p_age = self.p_age + 1
|
||||
def age(self) -> None:
|
||||
"""Increase days by one and grow plant"""
|
||||
self.days = self.days + 1
|
||||
self.grow()
|
||||
|
||||
def __init__(self, name: str, height: int, age: int) -> None:
|
||||
"""Init plant with his values and display his values"""
|
||||
self.name = name
|
||||
self.height = height
|
||||
self.days = age
|
||||
print("Created: ", end="")
|
||||
self.get_info()
|
||||
|
||||
if __name__ == "__main__":
|
||||
plant_1 = Plants("Rose", 50, 2)
|
||||
plant_2 = Plants("Chrysanthem", 30, 1)
|
||||
plant_3 = Plants("Rosemary", 60, 5)
|
||||
plant_4 = Plants("Cucumber", 40, 3)
|
||||
plant_5 = Plants("Salade", 15, 4)
|
||||
plants = [plant_1, plant_2, plant_3, plant_4, plant_5]
|
||||
|
||||
class PlantFactory:
|
||||
@staticmethod
|
||||
def create_plants(plants: list[tuple[str,
|
||||
int, int]]) -> list[Plant | None]:
|
||||
"""Create list of plants by list of arguments"""
|
||||
i = 0
|
||||
for n in plants:
|
||||
i = i + 1
|
||||
new_plants: list[Plant | None] = [None] * i
|
||||
i = 0
|
||||
for n in plants:
|
||||
new_plants[i] = Plant(n[0], n[1], n[2])
|
||||
i = i + 1
|
||||
return new_plants
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
plants = PlantFactory.create_plants([
|
||||
("Rose", 50, 2),
|
||||
("Chrysanthem", 30, 1),
|
||||
("Rosemary", 60, 5),
|
||||
("Cucumber", 40, 3),
|
||||
("Salade", 15, 4)
|
||||
])
|
||||
i = 0
|
||||
for n in plants:
|
||||
print("Created:", end=" ")
|
||||
n.get_info()
|
||||
i = i + 1
|
||||
print("\nTotal plants created:", i)
|
||||
|
||||
|
||||
@@ -4,33 +4,44 @@ class SecurePlant:
|
||||
__age: int
|
||||
|
||||
def set_height(self, height: int) -> None:
|
||||
"""Set height to plant"""
|
||||
if height < 0:
|
||||
print("Invalide operation attempted: height", height, "cm [REJECTED]")
|
||||
|
||||
print("Invalide operation attempted: height ",
|
||||
height, "cm [REJECTED]", sep="")
|
||||
print("Secrity: Negative height rejected")
|
||||
else:
|
||||
self.__height = height
|
||||
print("Height updated: ", height, "cm [OK]", sep="")
|
||||
|
||||
def set_age(self, age: int) -> None:
|
||||
"""Set age to plant"""
|
||||
if age < 0:
|
||||
print("Invalide operation attempted: age", age, "days [REJECTED]")
|
||||
print("Security: Negative age rejected")
|
||||
else:
|
||||
self.__age = age
|
||||
print("Age updated:", age, "days [OK]")
|
||||
|
||||
def get_height(self) -> int:
|
||||
"""Get plant height"""
|
||||
return self.__height
|
||||
|
||||
def get_age(self) -> int:
|
||||
"""Get plant age"""
|
||||
return self.__age
|
||||
|
||||
def __init__(self, name: str, height: int, age: int):
|
||||
def __init__(self, name: str, height: int, age: int) -> None:
|
||||
"""Init plant with his value"""
|
||||
self.name = name
|
||||
self.__height = height
|
||||
self.__age = age
|
||||
self.set_height(height)
|
||||
self.set_age(age)
|
||||
print("Plant created:", name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
plant = SecurePlant("Rose", 10, 3)
|
||||
print(plant.name, plant.get_height(), plant.get_age())
|
||||
plant.set_height(-10)
|
||||
plant.set_height(25)
|
||||
plant.set_age(30)
|
||||
print(plant.name, plant.get_height(), plant.get_age())
|
||||
plant.set_height(-10)
|
||||
print("Current plant: ", plant.name, " (", plant.get_height(),
|
||||
"cm, ", plant.get_age(), " days)", sep="")
|
||||
|
||||
@@ -1,37 +1,58 @@
|
||||
from typing_extensions import override
|
||||
|
||||
|
||||
class Plant:
|
||||
name: str
|
||||
height: int
|
||||
age: int
|
||||
|
||||
def __init__(self, name, height, age):
|
||||
def __init__(self, name: str, height: int, age: int) -> None:
|
||||
"""Init plant with his value"""
|
||||
self.name = name
|
||||
self.height = height
|
||||
self.age = age
|
||||
|
||||
def get_info(self):
|
||||
print(self.name.capitalize() + ":", self.height, end="")
|
||||
print("cm,", self.age, "days old")
|
||||
def get_info(self) -> None:
|
||||
"""Display plant informations"""
|
||||
print(f"{self.name}: {self.height}cm, {self.age} days")
|
||||
|
||||
|
||||
class Flower(Plant):
|
||||
color: str
|
||||
|
||||
def bloom(self):
|
||||
def bloom(self) -> None:
|
||||
"""Make flower blooming"""
|
||||
print(self.name + " is blooming beautifully !")
|
||||
|
||||
def __init__(self, name, height, age, color):
|
||||
@override
|
||||
def get_info(self) -> None:
|
||||
"""Display Flower info"""
|
||||
print(f"{self.name} (Flower): {self.height}cm,",
|
||||
f"{self.age} days, {self.color} color")
|
||||
|
||||
def __init__(self, name: str, height: int, age: int, color: str) -> None:
|
||||
"""Init flower with his value"""
|
||||
super().__init__(name=name, height=height, age=age)
|
||||
self.color = color
|
||||
|
||||
|
||||
class Tree(Plant):
|
||||
trunk_diameter: str
|
||||
trunk_diameter: int
|
||||
|
||||
def produce_shade(self):
|
||||
def produce_shade(self) -> None:
|
||||
"""Produce shade and display his size"""
|
||||
shade_size = self.height * self.trunk_diameter / 1000
|
||||
print(self.name, "provides", shade_size, "square meter")
|
||||
print(self.name, "provides", shade_size, "square meter of shade")
|
||||
|
||||
def __init__(self, name, height, age, trunk_diameter):
|
||||
@override
|
||||
def get_info(self) -> None:
|
||||
"""Display Tree info"""
|
||||
print(f"{self.name} (Tree): {self.height}cm,",
|
||||
f"{self.age} days, {self.trunk_diameter}cm diameter")
|
||||
|
||||
def __init__(self, name: str, height: int,
|
||||
age: int, trunk_diameter: int) -> None:
|
||||
"""Init tree with his value"""
|
||||
super().__init__(name=name, height=height, age=age)
|
||||
self.trunk_diameter = trunk_diameter
|
||||
|
||||
@@ -40,7 +61,19 @@ class Vegetable(Plant):
|
||||
harvest_season: str
|
||||
nutritional_value: str
|
||||
|
||||
def __init__(self, name, height, age, hs, nv):
|
||||
def print_nutritional_value(self) -> None:
|
||||
"""Display nutritional value"""
|
||||
print(f"{self.name} is rich in {self.nutritional_value}")
|
||||
|
||||
@override
|
||||
def get_info(self) -> None:
|
||||
"""Display Vegetable info info"""
|
||||
print(f"{self.name} (Vegetable): {self.height}cm,",
|
||||
f"{self.age} days, {self.harvest_season} harvest")
|
||||
|
||||
def __init__(self, name: str, height: int,
|
||||
age: int, hs: str, nv: str) -> None:
|
||||
"""Init vegetable with his value"""
|
||||
super().__init__(name=name, height=height, age=age)
|
||||
self.harvest_season = hs
|
||||
self.nutritional_value = nv
|
||||
@@ -49,11 +82,16 @@ class Vegetable(Plant):
|
||||
if __name__ == "__main__":
|
||||
flower0 = Flower("Rose", 30, 5, "red")
|
||||
flower1 = Flower("Chrysanthem", 50, 1, "yellow")
|
||||
tree0 = Tree("Platane", 300, 6, 30)
|
||||
tree1 = Tree("Sapin", 700, 15, 50)
|
||||
tree0 = Tree("Spruce", 300, 6, 30)
|
||||
tree1 = Tree("Oak", 700, 15, 50)
|
||||
vegetable0 = Vegetable("Salade", 30, 1, "Summer", "Vitamine c")
|
||||
vegetable1 = Vegetable("tomato", 200, 2, "Autumn", "Vitamine d")
|
||||
print(flower0.name, flower0.height, flower0.age, flower0.color)
|
||||
vegetable1 = Vegetable("Tomato", 200, 2, "Autumn", "Vitamine d")
|
||||
|
||||
flower0.get_info()
|
||||
flower0.bloom()
|
||||
print("")
|
||||
tree0.get_info()
|
||||
tree0.produce_shade()
|
||||
print(vegetable0.name, "is rich in", vegetable0.nutritional_value)
|
||||
print("")
|
||||
vegetable0.get_info()
|
||||
vegetable0.print_nutritional_value()
|
||||
|
||||
@@ -1,90 +1,179 @@
|
||||
class Plant:
|
||||
name: str
|
||||
height: int
|
||||
kind: str
|
||||
total_growth: int
|
||||
__kind: str
|
||||
|
||||
def __init__(self, name: str, height: int):
|
||||
def __init__(self, name: str, height: int) -> None:
|
||||
"""Init plant with his value"""
|
||||
self.name = name
|
||||
self.height = height
|
||||
self.kind = "regular"
|
||||
self.__kind = "regular"
|
||||
self.total_growth = 0
|
||||
|
||||
@classmethod
|
||||
def grow(self):
|
||||
def get_kind(self) -> str:
|
||||
"""Return __kind value"""
|
||||
return self.__kind
|
||||
|
||||
def set_kind(self, kind: str) -> None:
|
||||
"""Set __kind value"""
|
||||
self.__kind = kind
|
||||
|
||||
def grow(self) -> None:
|
||||
"""Grow the plant"""
|
||||
self.height = self.height + 1
|
||||
self.total_growth += 1
|
||||
|
||||
|
||||
class FloweringPlant(Plant):
|
||||
color: str
|
||||
blooming = False
|
||||
blooming: bool = False
|
||||
|
||||
def bloom (self):
|
||||
def bloom(self) -> None:
|
||||
"""Set blooming to true"""
|
||||
self.blooming = True
|
||||
print(self.name, "is blooming beautifully !")
|
||||
|
||||
def __init__(self, name, height, color):
|
||||
def __init__(self, name: str, height: int, color: str) -> None:
|
||||
"""Init Flowering plant with his value"""
|
||||
super().__init__(name=name, height=height)
|
||||
self.color = color
|
||||
self.kind = "flowering"
|
||||
self.set_kind("flowering")
|
||||
|
||||
|
||||
class PrizeFlower(FloweringPlant):
|
||||
prize: int
|
||||
|
||||
def __init__(self, name, height, color, prize):
|
||||
def __init__(self, name: str, height: int, color: str, prize: int) -> None:
|
||||
"""Init prize flower with his value"""
|
||||
super().__init__(name=name, height=height, color=color)
|
||||
self.prize = prize
|
||||
self.kind = "prize"
|
||||
self.set_kind("prize")
|
||||
|
||||
|
||||
class GardenManager:
|
||||
__gardens = {}
|
||||
gardens: dict[str, list[Plant | FloweringPlant | PrizeFlower]]
|
||||
nb_gardens: int
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Init garden manager"""
|
||||
self.gardens = {}
|
||||
self.nb_gardens = 0
|
||||
|
||||
class GardenStats:
|
||||
@staticmethod
|
||||
def garden_report(garden: []):
|
||||
i = 0
|
||||
for n in garden:
|
||||
i = i + 1
|
||||
n = 0
|
||||
while n < i:
|
||||
print(garden[n].name + ":", end=" ")
|
||||
print(garden[n].height, "cm", end="")
|
||||
if (garden[n].kind == "flowering" or garden[n].kind == "prize"):
|
||||
print(",", garden[n].color, "flowers", end=" ")
|
||||
if (garden[n].blooming):
|
||||
print("(blooming)", end="")
|
||||
if (garden[n].kind == "prize"):
|
||||
print(", Prize points:", garden[n].prize, end="")
|
||||
@classmethod
|
||||
def garden_report(cls,
|
||||
garden: list[Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower] | None) -> None:
|
||||
"""Start all garden report"""
|
||||
if garden is not None:
|
||||
cls.flower_in_garden(garden)
|
||||
print("")
|
||||
n = n + 1
|
||||
cls.added_plant_report(garden)
|
||||
cls.plants_in_garden(garden)
|
||||
else:
|
||||
print("Garden not provide")
|
||||
|
||||
@staticmethod
|
||||
def flower_in_garden(garden: list[Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower]) -> None:
|
||||
"""List flower in garden and display their status"""
|
||||
for n in garden:
|
||||
print("-", n.name + ":", end=" ")
|
||||
print(n.height, "cm", end="")
|
||||
if n.get_kind() == "flowering" or n.get_kind() == "prize":
|
||||
print(",", n.color, "flowers", end="")
|
||||
if n.blooming:
|
||||
print(" (blooming)", end="")
|
||||
if n.get_kind() == "prize":
|
||||
print(", Prize points:", n.prize, end="")
|
||||
print("")
|
||||
|
||||
@classmethod
|
||||
def get_garden(self, garden: str) -> []:
|
||||
return self.__gardens[garden]
|
||||
@staticmethod
|
||||
def added_plant_report(garden: list[Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower]) -> None:
|
||||
"""Report number of plant added to garden"""
|
||||
total_growth = 0
|
||||
total_plants = 0
|
||||
for n in garden:
|
||||
total_plants += 1
|
||||
total_growth += n.total_growth
|
||||
print(f"Plants added: {total_plants},",
|
||||
f"Total growth: {total_growth}cm")
|
||||
|
||||
@staticmethod
|
||||
def plants_in_garden(garden: list[Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower]) -> None:
|
||||
"""Report number of plant by types"""
|
||||
nb_regular = 0
|
||||
nb_flowering = 0
|
||||
nb_prize = 0
|
||||
for n in garden:
|
||||
if n.get_kind() == "regular":
|
||||
nb_regular += 1
|
||||
elif n.get_kind() == "flowering":
|
||||
nb_flowering += 1
|
||||
elif n.get_kind() == "prize":
|
||||
nb_prize += 1
|
||||
print(f"Plant types: {nb_regular} regular,",
|
||||
f"{nb_flowering} flowering, {nb_prize} prize flowers")
|
||||
|
||||
@classmethod
|
||||
def add_plant(self, garden: str, new_plant: Plant):
|
||||
if garden in self.__gardens:
|
||||
def get_nb_gardens(self) -> int:
|
||||
"""return the number of garden in the manager"""
|
||||
return self.nb_gardens
|
||||
|
||||
def get_garden(self, garden: str) -> list[Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower] | None:
|
||||
"""Return the plant list of the garden name provide if exist"""
|
||||
if garden in self.gardens:
|
||||
return self.gardens[garden]
|
||||
else:
|
||||
return None
|
||||
|
||||
def add_plant(self, garden: str, new_plant: Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower) -> None:
|
||||
"""Add one plant to the garden if exist"""
|
||||
if garden in self.gardens:
|
||||
i = 0
|
||||
for n in self.__gardens[garden]:
|
||||
for n in self.gardens[garden]:
|
||||
i = i + 1
|
||||
new = [None] * (i + 1)
|
||||
j = 0;
|
||||
new: list[Plant |
|
||||
FloweringPlant |
|
||||
PrizeFlower] = [Plant("", 0)] * (i + 1)
|
||||
j = 0
|
||||
while j < i:
|
||||
new[j] = self.__gardens[garden][j]
|
||||
new[j] = self.gardens[garden][j]
|
||||
j = j + 1
|
||||
new[i] = new_plant
|
||||
self.__gardens[garden] = new
|
||||
print("Added", new_plant.name, "to", garden, "'s garden")
|
||||
self.gardens[garden] = new
|
||||
print("Added ", new_plant.name, " to ",
|
||||
garden, "'s garden", sep="")
|
||||
else:
|
||||
print("Garden not found")
|
||||
|
||||
@classmethod
|
||||
def create_garden_network(self, garden_name: str) -> None:
|
||||
if garden_name in self.__gardens:
|
||||
"""Create a garden by name provide if it not exist"""
|
||||
if garden_name in self.gardens:
|
||||
print("garden already exist")
|
||||
else:
|
||||
self.__gardens[garden_name] = []
|
||||
self.gardens[garden_name] = []
|
||||
self.nb_gardens += 1
|
||||
|
||||
def grow_all(self, garden: str) -> None:
|
||||
"""Make all plant of one garden to grow"""
|
||||
if garden in self.gardens:
|
||||
print(f"{garden} is helping all plants grow...")
|
||||
for n in self.gardens[garden]:
|
||||
print(f"{n.name} grew 1cm")
|
||||
n.grow()
|
||||
else:
|
||||
print("Garden not found")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -99,6 +188,7 @@ if __name__ == "__main__":
|
||||
manager.add_plant("Alice", rose)
|
||||
manager.add_plant("Alice", sunflower)
|
||||
manager.add_plant("Bob", oak)
|
||||
|
||||
|
||||
manager.grow_all("Alice")
|
||||
manager.grow_all("Alice")
|
||||
print("\n\nGardenReport")
|
||||
manager.GardenStats.garden_report(manager.get_garden("Alice"))
|
||||
|
||||
@@ -10,7 +10,7 @@ def garden_operations(case: str) -> None:
|
||||
dic["a"]
|
||||
|
||||
|
||||
def test_error_types():
|
||||
def test_error_types() -> None:
|
||||
try:
|
||||
garden_operations("ValueError")
|
||||
except ValueError:
|
||||
|
||||
37
02/ex4/ft_raise_errors.py
Normal file
37
02/ex4/ft_raise_errors.py
Normal file
@@ -0,0 +1,37 @@
|
||||
def check_plant_health(plant_name, water_level, sunlight_hours):
|
||||
if not plant_name or not plant_name[0]:
|
||||
raise ValueError("Error: Plant name cannot be empty")
|
||||
elif water_level < 1:
|
||||
raise ValueError(f"Error: Water level {water_level} is too low (min 1)")
|
||||
elif water_level > 10:
|
||||
raise ValueError(f"Error: Water level {water_level} is too high (max 10)")
|
||||
elif sunlight_hours < 2:
|
||||
raise ValueError(f"Error: Sunlight hours {sunlight_hours} is too low (min 2)")
|
||||
elif sunlight_hours > 12:
|
||||
raise ValueError(f"Error: Sunlight hours {sunlight_hours} is too high (max 12)")
|
||||
else:
|
||||
print("Plant '" + plant_name + "' is healthy!")
|
||||
|
||||
|
||||
def test_plant_checks():
|
||||
try:
|
||||
check_plant_health("tomato", 5, 5)
|
||||
except ValueError as err:
|
||||
print(err)
|
||||
try:
|
||||
check_plant_health("salade", 0, 5)
|
||||
except ValueError as err:
|
||||
print(err)
|
||||
try:
|
||||
check_plant_health("carrots", 5, 20)
|
||||
except ValueError as err:
|
||||
print(err)
|
||||
try:
|
||||
check_plant_health("", 5, 5)
|
||||
except ValueError as err:
|
||||
print(err)
|
||||
print("All error raising tests completed!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_plant_checks()
|
||||
98
02/ex5/ft_garden_management.py
Normal file
98
02/ex5/ft_garden_management.py
Normal file
@@ -0,0 +1,98 @@
|
||||
from logging import raiseExceptions
|
||||
|
||||
|
||||
class Plant:
|
||||
__name: str
|
||||
__water: int
|
||||
__sun: int
|
||||
|
||||
@classmethod
|
||||
def set_name(cls, name: str) -> None:
|
||||
if not name or not name[0]:
|
||||
raise ValueError("Name cannot be empty")
|
||||
cls.__name = name
|
||||
|
||||
@classmethod
|
||||
def set_water(cls, water: int) -> None:
|
||||
if water < 0:
|
||||
raise ValueError("Water level cannot be negative")
|
||||
cls.__water = water
|
||||
|
||||
@classmethod
|
||||
def set_sun(cls, sun: int) -> None:
|
||||
if sun < 0:
|
||||
raise ValueError("Sun level cannot be negative")
|
||||
cls.__sun = sun
|
||||
|
||||
@classmethod
|
||||
def get_name(cls) -> str:
|
||||
return cls.__name
|
||||
|
||||
@classmethod
|
||||
def get_water(cls) -> int:
|
||||
return cls.__water
|
||||
|
||||
@classmethod
|
||||
def get_sun(cls) -> int:
|
||||
return cls.__sun
|
||||
|
||||
def __init__(self, name: str, water: int, sun: int) -> None:
|
||||
self.set_name(name)
|
||||
self.set_water(water)
|
||||
self.set_sun(sun)
|
||||
|
||||
|
||||
class GardenManager:
|
||||
__plants: list[Plant]
|
||||
__water_tank_level: int
|
||||
|
||||
@classmethod
|
||||
def get_water_tank_level(cls) -> int:
|
||||
return cls.__water_tank_level
|
||||
|
||||
@classmethod
|
||||
def set_water_tank_level(cls, level: int) -> None:
|
||||
cls.__water_tank_level = level
|
||||
|
||||
def add_plant(self, name: str, water: int, sun: int) -> None:
|
||||
try:
|
||||
new_plant = Plant(name, water, sun)
|
||||
i = 0
|
||||
for n in self.__plants:
|
||||
i = i + 1
|
||||
new_lst: list[Plant | None] = [None] * (i + 1)
|
||||
i = 0
|
||||
for n in self.__plants:
|
||||
new_lst[i] = n
|
||||
i = i + 1
|
||||
new_lst[i] = new_plant
|
||||
print("Added", name, "successfully")
|
||||
except ValueError as err:
|
||||
print(err)
|
||||
|
||||
def water_plants(self) -> None:
|
||||
print("Watering plants...")
|
||||
try:
|
||||
print("Opening watering system")
|
||||
for n in self.__plants:
|
||||
if self.__water_tank_level <= 0:
|
||||
raise Exception("Caught GardenError: Not enough water in tank")
|
||||
n.set_water(n.get_water() + 1)
|
||||
self.__water_tank_level = self.__water_tank_level - 1;
|
||||
print("Watering", n.get_name(), "- success")
|
||||
except Exception as err:
|
||||
print(err);
|
||||
finally:
|
||||
print("Closing watering system (cleanup)")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.__plants = []
|
||||
self.__water_tank_level = 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
manager = GardenManager()
|
||||
manager.set_water_tank_level(10)
|
||||
manager.add_plant("Tomato", 2, 10)
|
||||
manager.add_plant("Lettuce", 5, 7)
|
||||
manager.water_plants()
|
||||
14
03/ex0/ft_command_quest.py
Normal file
14
03/ex0/ft_command_quest.py
Normal file
@@ -0,0 +1,14 @@
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv
|
||||
if len(args) <= 1:
|
||||
print("No arguments provided !")
|
||||
print("Program name: " + args[0])
|
||||
if len(args) > 1:
|
||||
print("Arguments received:", len(args) - 1)
|
||||
i = 1
|
||||
while i < len(args):
|
||||
print("Argument", i, ":", args[i])
|
||||
i = i + 1
|
||||
print("Total arguments:", len(args))
|
||||
29
03/ex1/ft_score_analytics.py
Normal file
29
03/ex1/ft_score_analytics.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv
|
||||
if len(args) <= 1:
|
||||
print("No scores provided. Usage: python3 ft_score_analytics.py <score1> <score2> ...")
|
||||
else:
|
||||
scores = [0] * (len(args) - 1)
|
||||
i = 0
|
||||
try:
|
||||
while i < len(args) - 1:
|
||||
scores[i] = int(args[i + 1])
|
||||
i = i + 1
|
||||
print("Scores processed: [", end="")
|
||||
i = 0
|
||||
while i < len(scores):
|
||||
print(scores[i], end="")
|
||||
if not i == len(scores) - 1:
|
||||
print(", ", end="")
|
||||
i = i + 1
|
||||
print("]")
|
||||
print("Total players:", len(scores))
|
||||
print("Total score:", sum(scores))
|
||||
print("Average score:", sum(scores) / len(scores))
|
||||
print("High score:", max(scores))
|
||||
print("Low score:", min(scores))
|
||||
print("Score range", max(scores) - min(scores))
|
||||
except ValueError:
|
||||
print("Invalid input, only numbers are accepted")
|
||||
39
03/ex2/ft_coordinate_system.py
Normal file
39
03/ex2/ft_coordinate_system.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import math
|
||||
import sys
|
||||
|
||||
|
||||
def print_distance(a: tuple[int, int, int], b: tuple[int, int, int]) -> None:
|
||||
distance = math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
|
||||
print("Distance between (", end="")
|
||||
print(a[0], end="")
|
||||
print(", ", end="")
|
||||
print(a[1], end="")
|
||||
print(", ", end="")
|
||||
print(a[2], end="")
|
||||
print(") and (", end="")
|
||||
print(b[0], end="")
|
||||
print(", ", end="")
|
||||
print(b[1], end="")
|
||||
print(", ", end="")
|
||||
print(b[2], end="")
|
||||
print("):", distance)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
argv = sys.argv
|
||||
try:
|
||||
if len(argv) != 2:
|
||||
raise Exception("Invalid number of args")
|
||||
args = argv[1].split(',')
|
||||
if len(args) != 3:
|
||||
raise Exception("Invalid argument format." +
|
||||
"Try like this : \"15,64,78\"")
|
||||
int_args = (int(args[0]), int(args[1]), int(args[2]))
|
||||
print("Parsing coordinates:", args[1])
|
||||
print_distance((0, 0, 0), int_args)
|
||||
except ValueError as err:
|
||||
print("Parsing invalid coordinates: \"", end="")
|
||||
print(argv[1], end="\"\n")
|
||||
print(err)
|
||||
except Exception as err:
|
||||
print(err)
|
||||
Reference in New Issue
Block a user