在此特定代码中使用字符串匹配和任意参数

时间:2019-06-11 16:00:17

标签: python

我正在执行以下代码,其中

place_order(* item_tuple):此功能接受客户下达的订单。菜单为蔬菜卷,面条,炒饭和汤。该功能应检查所请求的物品是否存在于菜单中。供应商的菜单,如果有的话,则应通过调用check_quantity_available()方法检查所请求的数量是否可用于每个供应商。 check_quantity_available(index,quantity_requested) :此函数应检查所请求数量的指定项目是否可用。如果是这样,则应从该物料的可用数量中减少所请求的数量,并返回True。否则,它应该返回False。

 menu=('Veg Roll','Noodles','Fried Rice','Soup')
 quantity_available=[2,200,250,3]

 def place_order(*item_tuple):


 def check_quantity_available(index,quantity_requested):

 place_order("Veg Roll",2,"Noodles",2)
 place_order("Soup",1,"Veg Roll", 2, "Fried Rice1",1)

我期望的输出

Veg Roll is  available

Noodles is  available

由于我不清楚python代码,因此如何获取输出。

2 个答案:

答案 0 :(得分:1)

# menu=('Veg Roll','Noodles','Fried Rice','Soup')
# quantity_available=[2,200,250,3]



menudict={"Veg Roll":2,"Noodles":200,'Fried Rice':250,'Soup':3}



def place_order(*kwargs):
    countt=len(kwargs)
    for i in range(0,countt,2):
        if(not menudict.keys().__contains__(kwargs[i])):
            print("Item "+kwargs[i]+" is not available")
        elif(menudict[kwargs[i]]<kwargs[i+1]):
            print(kwargs[i] + " stock is over")
        else:
            menudict[kwargs[i]]-=kwargs[i+1]
            print(kwargs[i]+" is available")






# def check_quantity_available(index,quantity_requested):
#  pass
place_order("Veg Roll",2,"Noodles",2)
place_order("Soup",1,"Veg Roll", 2, "Fried Rice1",1)
  

使用字典非常容易。

答案 1 :(得分:0)

menu=('Veg Roll','Noodles','Fried Rice','Soup')
quantity_available=[2,200,250,3]



def place_order(*kwargs):
    countt=len(kwargs)
    for i in range(0,countt,2):
        index=1
        if kwargs[i] not in menu:
            print("Item "+kwargs[i]+" is not available")

        elif(check_quantity_available(kwargs[i],kwargs[i+1])):
            print(kwargs[i] + " stock is over")
            index = (menu.index(kwargs[i]))
        else:
            quantity_available[index]-=kwargs[i+1]
            index = (menu.index(kwargs[i]))
            print(kwargs[i]+" is available")



def check_quantity_available(name,quantiy):
 if quantity_available[menu.index(name)]<quantiy:
     return True
 else:
     return False

place_order("Veg Roll",2,"Noodles",2)
place_order("Soup",1,"Veg Roll", 2, "Fried Rice1",1)