【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方法一致
相关文章推荐
- 斯坦福大学开发PETE装置吸收60%的太阳能
- Codewars-Javascript训练手册:Date 对象
- codewars打怪升级日记 用JavaScript实现大数相加 /像数字一样加数字型字符串
- 【Codewars-Pyramid Slide Down】(下三角矩阵求最长路径)
- [codewars]2.编写一个maskify函数,把字符串除了后四位用“#”代替
- codewars解题笔记 —— 字符串匹配
- [Haskell] CodeWars|Sum of Digits
- 我爱codewars
- 数组排序、取字符串中的数字(codewars练习)
- Welcome to Pete Brown's 10rem.net
- Codewars-Javascript训练手册:正则表达式(上)
- [从codewars学习到的JS系列1]数组方法reduce(),map(),正则$1等的使用
- 【Codewars-snail】顺时针打印矩阵(python)
- [codewars]4.找到数组中唯一奇偶异常元素
- Rust: codewars的prize draw算法
- [Haskell] CodeWars|Bouncing Balls
- 今天,霍金没有提AI威胁论,他的新目标是带领人类移民外星球(附霍金姚期智Pete演讲实录+PPT)
- [Codewars]-Gap in Primes
- codewars - Broken Greetings
- 菜圈的codewars(一),codewars的注册