Python的简单题目

题目描述

考虑到他的食谱,他可以烤多少蛋糕?
编写一个函数cakes(),该函数接受食谱(对象)和可用成分(也是一个对象),
并返回 Pete 可以烘烤的最大蛋糕数(整数)。
为简单起见,数量没有单位(例如,1 磅面粉或 200 克糖只是 1 或 200)。
对象中不存在的成分可视为 0。
不能改变函数的接收值,此时结果为2

需要您

在此基础上改进一下,主要是不知道两个字典的顺序不一致怎么办

相关代码

def cakes(recipe, available):
    a = list(zip(recipe,available))
    print(a)
    recipe,available = list(recipe.values()),list(available.values())
    m = recipe.index(max(recipe))
    if len(recipe) > len(available):
        return 0
    res = available[m] // recipe[m]
    for y in recipe[1:]:
        x = [z-y*res for z in available[1:]]
        for i in x:
            if i >= 0:
                return res
            if i < 0:
                res -= 1

print(cakes({"flour": 500, "eggs": 1,"sugar": 200}, {"flour": 1200, "sugar": 1200, "eggs": 5, "milk": 200}))
阅读 2k
3 个回答
def cakes(recipe, available):
    return min(available.get(ingredient, 0) // num for ingredient, num in recipe.items())

对象是key:value 对,其实就是字典,不一定需要稳定的存储顺序,所以不存在顺序问题。
所以这个问题的简化处理其实是
math.floor(min(材料成分量1/食谱成分1,材料成分量2/食谱成分2,...,材料成分量n/食谱成分n))

def cakes(recipe, available):
    rt=max( tuple(available.values()))
    for k in recipe.keys():
        rt=min(rt, available.get(k,0)//recipe.get(k) )
        if(rt == 0):
            break;
    return rt
def cakes(recipe, available):
    res=0
    i=True
    if len(recipe) > len(available):
        return 0
    for key in recipe.keys():
        res2=available.get(key,0)//recipe[key]
        if i :
            res=res2
            i=False
        res=min(res,res2)
    return res
        

print(cakes({"flour": 500, "eggs": 1,"sugar": 200}, 
            {"sugar": 1500, "flour": 1200, "eggs": 5, "milk": 200}))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题