4 回答
TA贡献1942条经验 获得超3个赞
你可以使用字典。例如:
have = {"milk": 2, "eggs": 3, "flour": 0.5}
need = {"milk": 1, "eggs": 5, "flour": 2.5}
ingredients = {i:"Yes" if have[i] >= need[i] else "No" for i in have.keys()}
输出:
print(ingredients)
{'milk': 'Yes', 'eggs': 'No', 'flour': 'No'}
如果你想要一个函数来告诉你用你拥有的原料可以做多少蛋糕,你可以使用以下代码:
def how_many(need, have):
results = {i:have[i]//need[i] for i in have.keys()}
return min(results.values())
TA贡献1848条经验 获得超10个赞
假设输入如下
milk=200
eggs=10
flour=1000
milk_reqd=100
eggs_reqd=5
flour_reqd=2000
have=[milk, eggs, flour]
need=[milk_reqd, eggs_reqd, flour_reqd]
解决方案
import numpy as np
have=np.array(have)
need=np.array(need)
现在您可以执行所有操作,例如
need>have
或者
need<=have
或者
need-have
获取可以制作的蛋糕数量
n_cakes=int(min(have/need))
TA贡献1865条经验 获得超7个赞
如果你需要比较的数量列表,你可以使用单行列表理解(只能比较==,>,<否则如果你使用>=和<=和==它们将是重叠操作) -
milk_have = 10
eggs_have = 20
flour_have = 30
milk_need = 10
eggs_need = 25
flour_need = 3
have = [milk_have, eggs_have, flour_have]
need = [milk_need, eggs_need, flour_need]
['==' if i[0]==i[1] else '>' if i[0]>i[1] else '<' for i in zip(have, need)]
['==', '<', '>']
TA贡献1993条经验 获得超5个赞
have = ('milk', 'eggs', 'flour',"k")
need = ('milk', 'eggs', 'flour',"l")
incredients = {}
for i in range(len(have)):
count = 0
if have[i] == need[i]:
count +=1
incredients[have[i]] = count
输出:{'eggs': 1, 'flour': 1, 'k': 0, 'milk': 1}
添加回答
举报