I have list of this sort. It is the order list of a person:
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
#Here the second value is the quantity of the fruit to be purchased
How do I extract the string and the float value separately? I need to calculate the total order cost based on the given fruit prices:
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
This is what I have tried:
def buyLotsOfFruit(orderList):
"""
orderList: List of (fruit, numPounds) tuples
Returns cost of order
"""
totalCost = 0.0
length = len(orderList)
for i in range(0,length):
for j in range(0, length - i - 1):
totalCost = fruitPrices[orderList[i]] * orderList[j]
return totalCost
This yields wrong answer. What am I doing wrong? How can I fix this?
Thanks!
CodePudding user response:
Just iterate the list of tuple, and multiply each quantity with their price and pass the iterator to sum
function to get total
total = sum(qty*fruitPrices.get(itm,0) for itm,qty in orderList)
# 12.25
CodePudding user response:
You might use unpacking together with for
loop to get easy to read code, for example
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
total = 0.0
for name, qty in orderList:
total = qty * fruitPrices[name]
print(total) # 12.25
Note ,
inside for
...in
so name
values become 1st element of tuple and qty
becomes 2nd element of tuple.
CodePudding user response:
def buyLotsOfFruit(orderList, fruitPrices):
totalCost = 0.0
for order in orderList:
item, quantity = order
item_price = fruitPrices[item]
totalCost = (item_price * quantity)
return totalCost
CodePudding user response:
I change your code to don't get any errors.
Your orderList
is tuple you can accese each fruit_name
with [i][0]
and count with [i][1]
and for searching in dict
you can use dict.get(searching_key, value if not fount)
, You can change default value to any value you like, I set zero.
def buyLotsOfFruit(orderList, fruitPrices):
totalCost = 0.0
length = len(orderList)
for i in range(0,length):
totalCost = fruitPrices.get(orderList[i][0], 0) * orderList[i][1]
return totalCost
buyLotsOfFruit(orderList, fruitPrices)
You can use functools.reduce
to summarize your code.
>>> from functools import reduce
>>> reduce(lambda x,y : x fruitPrices.get(y[0],0)*y[1], orderList, 0)
12.25
12.25
CodePudding user response:
How about?
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
order_total = 0.00
You can iterate over the list of tuples and use name
to get the fruit name and quantity
to get the quantity. Using that you can look up the price value of the fruit from the fruitPrices dictionary using the key and multiple by the quantity, totalling as you go:
for name, quantity in orderList:
order_total = fruitPrices.get(name, 0) * quantity
print(order_total)
Then into your function would look like this:
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
def buyLotsOfFruit(orderList):
"""
orderList: List of (fruit, numPounds) tuples
Returns cost of order
"""
totalCost = 0.0
for name, quantity in orderList:
totalCost = fruitPrices.get(name, 0) * quantity
return totalCost
print(buyLotsOfFruit(orderList))
CodePudding user response:
Code:
order_list = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruit_prices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75, 'limes': 0.75, 'strawberries': 1.00}
def buyLotsOfFruit(order_list, fruit_prices):
total_cost = 0
for i in order_list:
total_cost = fruit_prices[i[0]] * i[1]
return total_cost
print(buyLotsOfFruit(order_list, fruit_prices))
Output:
12.25
Okay, so here is some explanation.
- Instead of getting the length of list we can just pass it and python will iterate over it's elements automaticly.
for i in order_list:
i
is the current tuple in order_list eg:[('apples', 2.0)
. So we can access it this way:i[0]
, we getapples
. And we use stringapples
to access apples price, you can imagine it this way:fruit_prices["apples"]
, and so we have price.- We get the amount we want, we use
i[1]
which returns2.0
in our exmaple with apples.
So you can image it looking like this:
total_cost = price * amount
And also we could do
total_cost = total_cost price * amount
but you can also use =
operator to simplify the expression.
CodePudding user response:
To fully understand and visualise your data, you can use pandas:
import pandas as pd
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
df = pd.DataFrame(orderList, columns = ['fruit', 'quantity'])
df['cost'] = df.apply( lambda row: row.quantity * fruitPrices[row.fruit], axis=1)
df
This returns:
fruit quantity cost
0 apples 2.0 4.00
1 pears 3.0 5.25
2 limes 4.0 3.00
To get total cost: df['cost'].sum()