Skip to content

Instantly share code, notes, and snippets.

@kshirsagarsiddharth
Last active July 18, 2020 17:55
Show Gist options
  • Select an option

  • Save kshirsagarsiddharth/a0ab241c7d03bace62cca7dd0fed4e8e to your computer and use it in GitHub Desktop.

Select an option

Save kshirsagarsiddharth/a0ab241c7d03bace62cca7dd0fed4e8e to your computer and use it in GitHub Desktop.
computing using tuples
# 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