-2

Create a tuple of grocery shopping items:

  1. total_price = qty*price (to be calculated).

  2. Calculate the grand total (total bill amount).

  3. Identify the costliest and the cheapest item.

Here is the code:

grocery = (
    ('butter', 'maggi', 'T-Shirt', 'Chocolate', 'Sanitizer'),
    (12, 10, 250, 80, 15),
    (10, 5, 2, 2, 5),   
    ()
)
merged_tuple = ((i[0], i[1], i[2],i[1]*i[2]) for i in grocery)
merged_tuple
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

0

To calculate the total price you can do the follow:

merged_tuple = (grocery[0],grocery[1], grocery[2], tuple(l * r for l, r in zip(grocery[1], grocery[2])))

merged_tuple

See this answer: Python Multiply tuples of equal length

With numpy:

merged_tuple = (grocery[0],grocery[1], grocery[2], tuple(np.array(grocery[1]) * np.array(grocery[2])))

Output:

(('butter', 'maggi', 'T-Shirt', 'Chocolate', 'Sanitizer'),
(12, 10, 250, 80, 15),
(10, 5, 2, 2, 5),
(120, 50, 500, 160, 75))
DavideBrex
  • 2,374
  • 1
  • 10
  • 23
  • 1
    You can use zip, map or numpy, but I think you need a function to do what you want – DavideBrex May 01 '20 at 07:57
  • @MiteshShah Did I answer to your question? If yes can you please accept my answer? Thank you – DavideBrex May 01 '20 at 09:21
  • Yes!! Thank-you so much!! – Mitesh Shah May 04 '20 at 10:39
  • merged_tuple=(('butter', 'maggi', 'Milk', 'Eggs', 'Chocolates'), (7, 10, 2, 12, 11), (3, 97, 24, 83, 81)) Here is nested tuple with items in 1st, 2nd is quantity and 3rd is the price... How can I print the costliest item (i.e Item having highest price) if(merged_tuple[0]==max(merged_tuple[2])): print(merged_tuple[0]) I tried this code but it is not working... Please Help – Mitesh Shah May 04 '20 at 10:42
  • import numpy as np; print(merged_tuple[0][np.argmax(merged_tuple[2])]) – DavideBrex May 04 '20 at 11:45