Python – 使用频率和价格字典计算成本
给定价格和频率字典,计算产品的总成本,即通过将每个项目的价格和频率的乘积相加。
Input : test_dict = {“Apple” : 2, “Mango” : 2, “Grapes” : 2}, {“Apple” : 2, “Mango” : 2, “Grapes” : 2}
Output : 12
Explanation : (2*2) + (2*2) + (2*2) = 12.
Input : test_dict = {“Apple” : 3, “Mango” : 2, “Grapes” : 3}, {“Apple” : 2, “Mango” : 2, “Grapes” : 2}
Output : 16
Explanation : The summation of product leads to 16 as above.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们遍历所有键并将每个元素的频率乘以其成本并继续执行中间求和。
Python3
# Python3 code to demonstrate working of
# Cost computation using Frequency and Price dictionary
# Using loop
# initializing dictionary
test_dict = {"Apple" : 5, "Mango" : 8, "Grapes" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing Frequency dict
cost_dict = {"Apple" : 3, "Mango" : 4, "Grapes" : 6}
res = 0
for key in test_dict:
# computing summation of product
res = res + (test_dict[key] * cost_dict[key])
# printing result
print("The extracted summation : " + str(res))
Python3
# Python3 code to demonstrate working of
# Cost computation using Frequency and Price dictionary
# Using sum() + list comprehension
# initializing dictionary
test_dict = {"Apple" : 5, "Mango" : 8, "Grapes" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing Frequency dict
cost_dict = {"Apple" : 3, "Mango" : 4, "Grapes" : 6}
# using list comprehension and sum() to provide one-liner
res = sum([cost_dict[key] * test_dict[key] for key in test_dict])
# printing result
print("The extracted summation : " + str(res))
输出
The original dictionary is : {'Apple': 5, 'Mango': 8, 'Grapes': 10}
The extracted summation : 107
方法 #2:使用 sum() + 列表推导
这些功能的组合提供了解决这个问题的捷径。在此,我们使用 sum() 执行求和,列表推导用于编译结果和迭代。
Python3
# Python3 code to demonstrate working of
# Cost computation using Frequency and Price dictionary
# Using sum() + list comprehension
# initializing dictionary
test_dict = {"Apple" : 5, "Mango" : 8, "Grapes" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing Frequency dict
cost_dict = {"Apple" : 3, "Mango" : 4, "Grapes" : 6}
# using list comprehension and sum() to provide one-liner
res = sum([cost_dict[key] * test_dict[key] for key in test_dict])
# printing result
print("The extracted summation : " + str(res))
输出
The original dictionary is : {'Apple': 5, 'Mango': 8, 'Grapes': 10}
The extracted summation : 107