I have list of this sort. It is the order list of a person:
JavaScript
x
3
1
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
2
#Here the second value is the quantity of the fruit to be purchased
3
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:
JavaScript
1
3
1
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
2
'limes':0.75, 'strawberries':1.00}
3
This is what I have tried:
JavaScript
1
13
13
1
def buyLotsOfFruit(orderList):
2
"""
3
orderList: List of (fruit, numPounds) tuples
4
5
Returns cost of order
6
"""
7
totalCost = 0.0
8
length = len(orderList)
9
for i in range(0,length):
10
for j in range(0, length - i - 1):
11
totalCost += fruitPrices[orderList[i]] * orderList[j]
12
return totalCost
13
This yields wrong answer. What am I doing wrong? How can I fix this?
Thanks!
Advertisement
Answer
You might use unpacking together with for
loop to get easy to read code, for example
JavaScript
1
8
1
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
2
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
3
'limes':0.75, 'strawberries':1.00}
4
total = 0.0
5
for name, qty in orderList:
6
total += qty * fruitPrices[name]
7
print(total) # 12.25
8
Note ,
inside for
…in
so name
values become 1st element of tuple and qty
becomes 2nd element of tuple.