iT邦幫忙

2022 iThome 鐵人賽

DAY 26
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 26

[Day26] Codewars >>> Pete, the baker (Python)

  • 分享至 

  • xImage
  •  

題目(5kyu):

Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is >not good in maths. Can you help him to find out, how many cakes he could bake >considering his recipes?

Write a function cakes(), which takes the recipe (object) and the available ingredients >(also an object) and returns the maximum number of cakes Pete can bake (integer). For >simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are >simply 1 or 200). Ingredients that are not present in the objects, can be considered as >0.

Examples:

#must return 2
cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: >200})
#must return 0
cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: >2000, milk: 2000})

解題思路

題目理解:編寫一個函式接受兩參數,食譜recipe&可用食材available。兩者皆為字典形式,其key為食材成分,並有對應的值。根據食譜recipe所表達製作一份的需求量,來計算可用食材available能製作多少份並返還數量。

def cakes(recipe, available):
    lst = []
    #檢驗每項recipe中食材是否有出現在available中
    for ing in recipe.keys():
        #若available缺少食譜中食材則直接返還0 
        if ing not in available.keys():
            return 0
        #將可用食材的數量/食譜指定數量,用int()取整即為單品項成分可製作的份數並存入lst
        lst.append(int(available[ing]/recipe[ing]))
    return min(lst)

上一篇
[Day25] Codewars >>> Decimal to Factorial and Back (Python)
下一篇
[Day27] Codewars >>> First non-repeating character (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言