我有一個 PizzaPriceCalculator 函式,它接受 3 個引數:醬汁(字串)、澆頭(最初是字串)和忠誠客戶(布林值)。
我有 2 個字典:這樣的 sauceMenu 和 toppingsMenu:
sauceMenu = {
"regular": 4.35,
"alfredo": 4.6,
"marinara": 5.85,
"mix": 5.47
}
toppingsMenu = {
"cheese": 0.5,
"pepperoni": 0.75,
"salami": 0.65,
"olives": 1.0,
"mushroom": 0.35
}
函式是這樣呼叫的:
pizzaPriceCalculator("marinara", "pepperoni", True)
我只是遍歷兩個字典,如果有匹配和總和醬的回傳成本以及列印最終價格的澆頭成本。
這是完整的代碼:
def pizzaPriceCalculator (sauce, toppings, loyalCustomer):
sauceMenu = {
"regular": 4.35,
"alfredo": 4.6,
"marinara": 5.85,
"mix": 5.47
}
toppingsMenu = {
"cheese": 0.5,
"pepperoni": 0.75,
"salami": 0.65,
"olives": 1.0,
"mushroom": 0.35
}
for i in sauceMenu:
if sauce is i:
print(sauceMenu[i])
baseTeaAmount = sauceMenu[i]
for j in toppingsMenu:
if toppings is j:
print(toppingsMenu[j])
toppingsAmount = toppingsMenu[j]
priceBeforeDiscount = baseTeaAmount toppingsAmount
print(priceBeforeDiscount)
if loyalCustomer:
priceAfterDiscount = priceBeforeDiscount - 1
print(priceAfterDiscount)
# return priceAfterDiscount;
pizzaPriceCalculator("marinara", "pepperoni", True)
問題是我被告知要重構代碼并使第二個引數(澆頭)成為字串串列,以便您可以選擇許多澆頭。
pizzaPriceCalculator("marinara", ["pepperoni", "cheese", "olives"], True)
如何匹配陣列迭代器和物件迭代器,以便將醬汁和所有配料相加?
我嘗試遍歷澆頭串列(來自輸入)并檢查它是否與我們的 toppingsMenu 字典迭代器匹配,但它不起作用:
for j in toppingsMenu:
for k in toppings:
if toppings[k] is j:
print(toppingsMenu[j])
toppingsAmount = toppingsMenu[j]
另外,我如何將所有挑選的頂部價格相互添加,最后添加到醬汁價格以獲得最終成本?
任何建議表示贊賞。
uj5u.com熱心網友回復:
按照下面的代碼。假設,對于醬汁,輸入只是字串中的一項,而澆頭將是許多專案的串列......
def pizzaPriceCalculator (sauce, toppings, loyalCustomer):
sauceMenu = {"regular": 4.35, "alfredo": 4.6, "marinara": 5.85, "mix": 5.47}
toppingsMenu = {"cheese": 0.5, "pepperoni": 0.75, "salami": 0.65, "olives": 1.0, "mushroom": 0.35}
baseTeaAmount = sauceMenu[sauce]
toppingsAmount = 0
for item in toppings:
toppingsAmount = toppingsAmount toppingsMenu[item]
priceBeforeDiscount = baseTeaAmount toppingsAmount
if loyalCustomer:
priceAfterDiscount = priceBeforeDiscount - 1
print(priceAfterDiscount)
else:
print(priceBeforeDiscount)
pizzaPriceCalculator("marinara", ["pepperoni", "cheese", "olives"], True)
# 7.1 (output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511147.html
下一篇:從多個列與多個列創建列聯表
