Answer:
def shopSmart(orderList, fruitShops): #function definition
shop = fruitShops[0] #sets the shop to first item of fruitShops list
leastAmount = shop.getPriceOfOrder(orderList) #passes the orderList to getPriceOfOrder method which returns the total cost and saves it to leastAmount
for fruitshop in fruitShops[1:]: #iterates through the shops in fruitShops list
cost = fruitshop.getPriceOfOrder(orderList) #checks each cost or order using getPriceOfOrder method and passing orderList to it
if cost < leastAmount: #checks where order costs the least amount in total
shop = fruitshop #sets the FruitShop where order costs the least amount in total
leastAmount = cost #sets that minimum of order cost to leastAmount
return shop #returns the FruitShop where order costs the least amount in total
Step-by-step explanation:
Here are the getPriceOfOrder() and getName()) methods that is used in the above method.
def getPriceOfOrder(self, orderList):
totalCost = 0.0
for fruit, numPounds in orderList:
costPerPound = self.getCostPerPound(fruit)
if costPerPound != None:
totalCost += numPounds * costPerPound
return totalCost
def getName(self):
return self.name
Here is the main program:
orders = [('apples',1.0), ('oranges',3.0)]
dir1 = {'apples': 2.0, 'oranges':1.0}
shop1 = shop.FruitShop('shop1',dir1)
dir2 = {'apples': 1.0, 'oranges': 5.0}
shop2 = shop.FruitShop('shop2',dir2)
shops = [shop1, shop2]
print("For orders ", orders, ", the best shop is", shopSmart(orders, shops).getName())
orders = [('apples',3.0)]
print("For orders: ", orders, ", the best shop is", shopSmart(orders, shops).getName())
Notice that the statement:
print("For orders ", orders, ", the best shop is", shopSmart(orders, shops).getName())
has orders list which is:
[('apples',1.0), ('oranges',3.0)]
and it has shops which is a list containing two shops:
shops = [shop1, shop2]
It also calls method shopSmart by passing orders and these two shops to get the shop where the order costs the least amount in total. It has a for loop that iterates through each shop and check the orders using getPriceOfOrder method to determine at which shop the order costs the least amount in total. When the least amount is found it is set to the variable leastAmount and the shop corresponding to this order which has least amount is set to shop variable. At the end this shop is returned by the function. getName() method is used in the main program to get the name of the shop with least amount of order cost. So above print statement gives the following output:
For orders [('apples', 1.0), ('oranges', 3.0)] , the best shop is shop1
The entire program along with its output is attached.