python字典问题

假定一款游戏中,共有A B C D四种商品,每种商品的金币价格存在字典price={' A':20,' B':30,'C':40,' D':50}。编写一个程序输入一个金币值以及若干商品名称判断若能购买这些商品则输出yes,否则则输出no。

稍等,帮你写,人工回答,需要时间。

price = {'A': 20, 'B': 30, 'C': 40, 'D': 50}
coin = int(input(""))
items = input("").upper().split()
total_price = sum([price[item] for item in items if item in price])
if total_price <= coin:
    print("yes")
else:
    print("no")


price = {'A': 20, 'B': 30, 'C': 40, 'D': 50}

def can_buy(gold, items):
    total_cost = 0
    for item in items:
        if item in price:
            total_cost += price[item]
    if total_cost <= gold:
        return 'yes'
    else:
        return 'no'

gold_value = int(input("请输入金币值:"))
items_to_buy = input("请输入要购买的商品名称(用空格分隔):").split()

print(can_buy(gold_value, items_to_buy))

定义了商品价格字典price,接着定义了一个名为can_buy的函数,该函数接受两个参数,一个是金币值,一个是要购买的商品名称列表,然后计算所有商品的总价值,如果总价值小于等于金币值,则返回'yes',否则返回'no'。程序会先提示用户输入金币值和要购买的商品名称,然后将商品名称列表作为参数调用can_buy函数,并输出返回值。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^