Advertisement
SimeonTs

SUPyF2 Objects/Classes-Exericse - 03. Catalogue

Oct 19th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. """
  2. Objects and Classes - Exericse
  3. Check your code: https://judge.softuni.bg/Contests/Practice/Index/1734#2
  4.  
  5. SUPyF2 Objects/Classes-Exericse - 03. Catalogue
  6.  
  7. Problem:
  8. Create a class Catalogue. The __init__ method should accept the name of the catalogue.
  9. Each catalogue should also have an attribute called products and it should be a list.
  10. The class should also have three more methods:
  11. • add_product(product) - add the product to the product list
  12. • get_by_letter(first_letter) - returns a list containing only the products that start with the given letter
  13. • __repr__ - returns the catalogue info in the following format:
  14. "Items in the {name} catalogue:
  15. {item1}
  16. {item2}"
  17. The items should be sorted alphabetically (default sorting)
  18.  
  19. Examples:
  20. Test Code:
  21. catalogue = Catalogue("Furniture")
  22. catalogue.add_product("Sofa")
  23. catalogue.add_product("Mirror")
  24. catalogue.add_product("Desk")
  25. catalogue.add_product("Chair")
  26. catalogue.add_product("Carpet")
  27. print(catalogue.get_by_letter("C"))
  28.  
  29. Output:
  30. ['Chair', 'Carpet']
  31. Items in the Furniture catalogue:
  32. Carpet
  33. Chair
  34. Desk
  35. Mirror
  36. Sofa
  37. """
  38.  
  39.  
  40. class Catalogue:
  41.     def __init__(self, name: str):
  42.         self.name = name
  43.         self.products = []
  44.  
  45.     def add_product(self, product):
  46.         self.products.append(product)
  47.  
  48.     def get_by_letter(self, first_letter):
  49.         f_l_list = [pr for pr in self.products if pr[0] == first_letter]
  50.         return f_l_list
  51.  
  52.     def __str__(self):
  53.         result = ''
  54.         result_list = [x for x in sorted(self.products)]
  55.         result += f"Items in the {self.name} catalogue:\n"
  56.         result += f"\n".join(result_list)
  57.         return result
  58.  
  59.  
  60. catalogue = Catalogue("Furniture")
  61. catalogue.add_product("Sofa")
  62. catalogue.add_product("Mirror")
  63. catalogue.add_product("Desk")
  64. catalogue.add_product("Chair")
  65. catalogue.add_product("Carpet")
  66. print(catalogue.get_by_letter("C"))
  67. print(catalogue)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement