Skip to content

Conversation

@eduardzapadinsky
Copy link
Owner

No description provided.

Copy link
Contributor

@shorodilov shorodilov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Треба зробити рефакторінг та додати відсутні методи.

01/task_01.py Outdated

def get_total(self, count: float):
"""Calculating total price for the product"""
return self.price * count
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут треба полагодити, бо можлива неочікувана поведінка.
Наприклад

product = Product("product", 15.10)
product.get_total(0.7)

01/task_01.py Outdated
"""Adding products and calculating total sum"""

self.products[product] += count
self.total += product.price * count
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Он у тебе више є метод для цього.

01/task_01.py Outdated
"""Describing shopping cart"""

def __init__(self):
self.products = defaultdict(int)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не складай кастомні об'єкти без __hash__ до ключей словника.
Використовуй список.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Або роби реалізацію __hash__, проте списки ліпше.

@eduardzapadinsky
Copy link
Owner Author

Округлив суму. Використав список замість словника. Додав метод для підрахунку суми замість атрибута.

@shorodilov shorodilov self-requested a review November 25, 2022 14:24
Copy link
Contributor

@shorodilov shorodilov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Треба зберігати інформацію про кількість товарів у кошику.

01/task_01.py Outdated
"""Adding products to the cart"""

total_product_price = product.get_total(count)
self.total_cart.append(total_product_price)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

За такої реалізації легше було зробити одне поле, куди складати суму покупки.
Але таким чином проігноровано умову, зберігати кільсть товару у кошику.
Це треба доробити.

@eduardzapadinsky
Copy link
Owner Author

Додав ще розрахунок загальної к-ті товарів в кошику, правильно? Чи треба назву кожного товару та його кількість?

@shorodilov
Copy link
Contributor

Додав ще розрахунок загальної к-ті товарів в кошику, правильно? Чи треба назву кожного товару та його кількість?

Так, окремо товар та його кількість.
Уяви, що наступним завданням я попрошу тебе створити метод, що буде друкувати чек на продуктовий кошик.

@eduardzapadinsky
Copy link
Owner Author

Змінив на словник products_list, де міститься товар, його ціна, к-сть та сума, як в чеку. Загальна суму тепер береться з цього словника

@shorodilov
Copy link
Contributor

Змінив на словник products_list, де міститься товар, його ціна, к-сть та сума, як в чеку. Загальна суму тепер береться з цього словника

Ок, а як мені дістатись до об'екту товару?
Припустимо, мені знадобиться якись ще метод від класу Product - а у тебе сам об'єкт не збережено.

Copy link
Contributor

@shorodilov shorodilov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Губиш об'єкти товарів при додавані до кошика.

01/task_01.py Outdated
"""Adding products to the cart"""

if product.name in self.products_list:
quantity = self.products_list.get(product.name, 0)["quantity"] + count
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Це важко читати. У такому випадку ліпше розбити на декілька рядків.

01/task_01.py Outdated
quantity = self.products_list.get(product.name, 0)["quantity"] + count
else:
quantity = count
product_sum = product.get_total(quantity)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

От цьому тут явно не місце

01/task_01.py Outdated
quantity = count
product_sum = product.get_total(quantity)
price = product.price
self.products_list[product.name] = {"quantity": quantity, "price": price, "product_sum": product_sum}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У тебе губиться об'ект, тобто якщо знадобиться ще якийсь метод класу Product- то це буде неможливо.

@eduardzapadinsky
Copy link
Owner Author

Додав об'єкт замість атрибутів продукта. Переніс підрахунок суми в метод суми. Правильно зрозумів?

Copy link
Contributor

@shorodilov shorodilov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Метод ShoppingCart.get_total потребує рефакторінгу.

01/task_01.py Outdated
for item in self.products_list:
p_price = self.products_list[item]['product'].price
quantity = self.products_list[item]["quantity"]
product_list_sum += p_price * quantity
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Використовуй для цього Product.get_total

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

І про округлення не забувай.

product_1 = Product("product #1", 10.59)
product_2 = Product("product #2", 36.55)
cart = ShoppingCart()
cart.add_product(product_1, 0.7)
cart.add_product(product_2, 4)
cart.get_total()

@eduardzapadinsky
Copy link
Owner Author

Переробив з використанням get_total та перевірив ще раз на округлення

Copy link
Contributor

@shorodilov shorodilov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Треба виправити зберігання товарів у кошику - тип ключа або власне тип змінної контейнера.
Метод для підрахунку суми товарів у кошику потребує рефакторінгу.

01/task_01.py Outdated
"""Describing the shopping cart"""

def __init__(self):
self.products_list = {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Погана ідея використовувати словник з кастомним класом без __eq__ та __hash__ у якості ключа.
Розвали цю штуку на два списки - за швидкістю не втратиш, але спростиш реалізацію.
Якщо дуже бажаєш мати словник, то ключем я б радив взяти product.name (str) або (product.name, product.price) (tuple).

01/task_01.py Outdated
product = self.products_list[item]['product']
quantity = self.products_list[item]["quantity"]
product_list_sum += product.get_total(quantity)
return product_list_sum
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

От тут буде проблема

product_1 = Product("foo", 10.59)
product_2 = Product("bar", 36.55)
cart = ShoppingCart()
cart.add_product(product_1, 0.7)
cart.add_product(product_2, 4)
cart.total_cart_sum()

01/task_01.py Outdated
"""Calculating the total cart sum"""

product_list_sum = 0
for item in self.products_list:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Бачиш, не зручно ітеруватись за словником, бо у тебе доволі важкі структуру даних.
Якщо розбити на списки - буде набагато легше.

@eduardzapadinsky
Copy link
Owner Author

Розбив на 2 списки - окремо по екземплярам класу Product, та окремо кількості. Суму подраховую беручи дані з цих списків. Також додав округлення до суми, хоча так і не зрозумів, чому до кожного окремого об'єкту метод get_total округляє, а в сумі чомусь не округляє.

Copy link
Contributor

@shorodilov shorodilov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

01/task_01.py Outdated
product.name, 0
)["quantity"] + count
if product in self.products_list:
self.products_count[self.products_list.index(product)] += count
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так норм, але важко читати - краще розбити на два рядки.

01/task_01.py Outdated
cart1.add(prod1, 5)
print(cart1.products_list)
print(cart1.total_cart_sum())
for i in range(len(self.products_list)):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for i in range(len(self.products_list)):
for product, count in zip(self.products_list, self.products_count):

@eduardzapadinsky
Copy link
Owner Author

eduardzapadinsky commented Nov 27, 2022

Поправив, дякую

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants