Search code examples
pythonlogic

Compute bill for a gem store


Below is my code to compute the bill for the gem store. I'm able to get correct prices for the right elements from the list but I'm not able to figure out how to multiply them with the required quantity (reqd_qty list) and calculate the total price.

Following is the complete problem description.

Tanishq Gems Store sells different varieties of gems to its customers.

Write a Python program to calculate the bill amount to be paid by a customer based on the list of gems and quantity purchased. If any gem required by the customer is not available in the store, then consider the total bill amount to be -1.

Assume that quantity required by the customer for any gem will always be greater than 0

def calculate_bill_amount(gems_list, price_list, reqd_gems,reqd_quantity):
bill_amount=0
#Write your logic here
for gem in gems_list:
    for g in reqd_gems:
        if g==gem:
            index = gems_list.index(g)
            price = price_list[index]
            print(price) 


return bill_amount

#List of gems available in the store
gems_list=["Emerald","Ivory","Jasper","Ruby","Garnet"]

#Price of gems available in the store. gems_list and price_list have one-to- 
one correspondence
price_list=[1760,2119,1599,3920,3999]

#List of gems required by the customer
reqd_gems=["Ivory","Emerald","Garnet"]

#Quantity of gems required by the customer. reqd_gems and reqd_quantity have 
one-to-one correspondence
reqd_quantity=[3,2,5]

bill_amount=calculate_bill_amount(gems_list, price_list, reqd_gems, 
reqd_quantity)
print(bill_amount)

Current Output:

1760 # Ivory Price
2119 # Emerald Price
3999 # Garnet Price
0 # Bill amount

Solution

  • I suggest you read up on dictionaries, looping over lists to match a value in another list is very inefficient. https://docs.python.org/3/tutorial/datastructures.html#dictionaries

    gems_list = ["Emerald", "Ivory", "Jasper", "Ruby", "Garnet"]
    price_list = [1760, 2119, 1599, 3920, 3999]
    reqd_gems = ["Ivory", "Emerald", "Garnet"]
    reqd_quantity = [3, 2, 5]
    
    quantity_dict = dict(zip(reqd_gems, reqd_quantity))
    price_dict = dict(zip(gems_list, price_list))
    print("Item", "Quantity", "Unit_price", "Total_price")
    for k, v in quantity_dict.items():
        print(k, v, price_dict[k], price_dict[k] * v)
    print("Grand_total", sum([price_dict[k] * v for k, v in quantity_dict.items()]))