Last active
July 18, 2020 17:55
-
-
Save kshirsagarsiddharth/a0ab241c7d03bace62cca7dd0fed4e8e to your computer and use it in GitHub Desktop.
computing using tuples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # consider a shopping list which contains various objects with quantity and cost and this items are stored in a list as tuples with their description and we want to find the total cost with discount | |
| from collections import namedtuple | |
| grocery = namedtuple('grocery',['item_name','item_weight','item_cost', | |
| 'item_quantity','item_dicsount']) | |
| shopping_list_tuples = [('apples',2.3,128,7,13.6),('chicken',1,228,2,110), | |
| ('milk',0.6,18,2,0),('lemons',0.3,45,20,50)] | |
| def total_cost_tuples(shopping_list): | |
| total = 0 | |
| for val in shopping_list: | |
| # here we are multiplying cost with number and subtracting it by discount | |
| total += val[2] * val[3] - val[4] | |
| return total | |
| print(total_cost_tuples(shopping_list_tuples)) | |
| # Output: 2114.4 | |
| def total_cost_named_tuples(shopping_list): | |
| total = 0 | |
| for val in shopping_list: | |
| # here we are multiplying cost with number and subtracting | |
| it by discount | |
| g = grocery(*val) | |
| total += g.item_cost * g.item_quantity - g.item_dicsount | |
| return total | |
| print(total_cost_named_tuples(shopping_list_tuples)) | |
| # Output: 2114.4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment