PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

[FIXED] How to calculate total price with discount by the products in Python

 October 25, 2022     oop, python     No comments   

Issue

I created two classes. In class Cart i need to implement the method get_total_price that calculate total price with discount. Discount depends on count product:

count        discount
at least 5     5%
at least 7     10%
at least 10    20%
at least 20    30%
more than 20   50%
class Product:
    
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count = count


class Cart:
    
    def __init__(self, *products_list):
        self.products_list = products_list
    
    def get_total_price(self):
        pass

        
products = (Product('p1',10,4),
Product('p2',100,5),
Product('p3',200,6),
Product('p4',300,7),
Product('p5',400,9),
Product('p6',500,10),
Product('p7',1000,20))
cart = Cart(products)
print(cart.get_total_price())
The result of running the program should be 24785.0

Can someone help, because I can not figure out how to get the attributes(price, count) to calculate the discount.


Solution

It seems cart.products_list returns a tuple containing the products list (so, a tuple in another tuple). If it's not intended, remove the '*'.

Here is a working solution for the current structure; if you remove '*', remove [0] in the get_total_price method.

def discount_mult(q):
        if q > 20:
            return .5
        elif q >= 20:
            return .7
        elif q >= 10:
            return .8
        elif q >= 7:
            return .9
        elif q >= 5:
            return .95
        else:
            return 1    

class Product:    
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count =  count    

class Cart:        
    def __init__(self, *products_list):
        self.products_list = products_list
    
    def get_total_price(self):
        return sum([i.price*i.count*discount_mult(i.count) for i in self.products_list[0]])

        
products = (Product('p1',10,4),Product('p2',100,5),Product('p3',200,6),Product('p4',300,7),
            Product('p5',400,9),Product('p6',500,10),Product('p7',1000,20))
cart = Cart(products)
print(cart.get_total_price())


Answered By - Swifty
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing