您的位置:首页 > 编程语言 > Python开发

【codewars】Pete, the baker

2017-12-22 19:45 429 查看

instruction

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:



my solution

def cakes(recipe, available):
n = []
for re in recipe:
if re in available.keys():
num = int(available[re]/recipe[re])
n.append(num)
else:
return 0
return min(n)


best solution from others

def cakes(recipe, available):
return min(available.get(k, 0) / v for k, v in recipe.iteritems())


get方法

返回指定键的值,如果值不在字典中返回默认值

dict.get(key, default=None)

key – 字典中要查找的键

default – 如果指定键的值不存在时,返回该默认值

dict = {'Name': 'Runoob', 'Age': 27}
print ("Age 值为 : %s" %  dict.get('Age'))

>>> Age 值为 : 27


dict = {'Name': 'Runoob', 'Age': 27}
print ("Sex 值为 : %s" %  dict.get('Sex', "boy"))

>>> Sex 值为 : boy


items方法

字典 items() 方法以列表返回可遍历的(键, 值) 元组数组

dict.items()

返回值 - 返回可遍历的(键, 值) 元组数组

dict = {'Name': 'Runoob', 'Age': 7}
print ("Value : %s" %  dict.items())

>>> Value : dict_items([('Age', 7), ('Name', 'Runoob')])


遍历栗子

dict = {'Name': 'Runoob', 'Age': 7}
for i,j in dict.items():
print(i, ":\t", j)

>>> Name :   Runoob
>>> Age :    7


Python2.x:

items( )用于 返回一个字典的拷贝列表,占额外的内存,iteritems() 用于返回本身字典列表操作后的迭代,不占用额外的内存

Python 3.x

iteritems() 和 viewitems() 这两个方法都已经废除

items() 得到的结果是和 2.x 里面 viewitems() 一致

在3.x 里 用 items()替换iteritems() ,可以用于 for 来循环遍历

max方法

返回给定参数的最大值,参数可以为序列

max( x, y, z, …. )

x - 数值表达式

y - 数值表达式

z - 数值表达式

返回值 - 返回给定参数的最大值

a = [1,2,3,7,8,9]
print(max(a))

>>> 9


a = ["a","b","c"]
print(max(a))

>>> c


a = (1,2,3)
print(max(a))

>>> 3


a = {"xy":999,"yz":88,"zx":7}
print(max(a))

>>> zx


min方法为返回给定参数的最小值,使用方法与max方法一致
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python codewars