[英]All combinations in list of list or dictionary
使用Python:
我有一本字典,其中的“鍵”代表硬幣的價值。 “值”代表該硬幣的數量。
如:
dict = {2: [0], 1: [0], 0.5: [0], 0.2: [0], 0.1: [0], 0.05: [1], 0.02: [1, 1, 1, 1], 0.01: [1, 1, 1]}
要么
dict = {2: [], 1: [], 0.5: [], 0.2: [], 0.1: [], 0.05: [1], 0.02: [1, 1, 1, 1], 0.01: [1, 1, 1]}
要么
dict = {2: 0, 1: 0, 0.5: 0, 0.2: 0, 0.1: 0, 0.05: 1, 0.02: 4, 0.01: 3}
(我不確定哪個最好用-它也可以只表示為8個整數的列表,例如[0,0,0,0,0,0,1,4,3]或列表的列表,例如[ [],[],[],[],[],[1],[1,1,1,1],[1,1,1]])
我想創建一個字典,顯示所有不同硬幣的所有可能組合,其中“鍵”將是硬幣的總值,“值”將是表示每個硬幣數量的8個整數的列表。
編輯:我意識到我想用詞典做的事情是不可能的,因為您不能對一個鍵名進行多次分配:如何使用函數itertools.combinations(iterable,r)返回一個元組列表?
我認為解決此問題的最簡單方法是使用itertools.combinations
。
要使用此功能,您首先需要將您的硬幣計數dict
轉換為硬幣list
:
coins = {2: 0, 1: 0, 0.5: 0, 0.2: 0, 0.1: 0, 0.05: 1, 0.02: 4, 0.01: 3}
# stores a list of all coin values, ie [0.2, 0.2, 1] if one has two 20c and 1 $1
coin_list = []
for value, count in coins.items():
if count > 0:
coin_list += [value] * count
然后,可以使用itertools.combinations
來獲取每種可能的組合大小的每種可能的組合,對其求和,然后將其保存到輸出dict
。
由於要存儲每個值的硬幣的所有可能組合,因此可以將dict
中的每個項目轉換為一set
collections.Counter
。 該set
將僅存儲唯一的硬幣計數:
import itertools
import collections
output_dict = dict()
for comb_size in range(len(coin_list)):
# gets every combination of every size from coin_list
for combination in itertools.combinations(coin_list, comb_size):
# sums up all coins in combination
value = sum(combination)
# get the set of existing coins for value/create if it doesn't exist
value_set = output_dict.get(value, set())
# collections.Counter counts up each coin in a combination
counter = collections.Counter(combination)
# we need to convert counter to a hashable form to add it to a set()
value_set.add(tuple(sorted(counter.items())))
output_dict[value] = value_set
最后,由於加總浮點會導致奇怪的結果(例如0.1 + 0.2 = 0.300000001
),因此在打印時,您可以將總和的值四舍五入到最接近的美分(並使用模塊pprint
使格式更好):
import pprint
pprint.pprint({round(x, 2): y for x,y in output_dict.items()})
這將打印出一個dict
的set
每個硬幣價值總和。 每個set
包含tuples
對的(硬幣值,硬幣的數量),即,對於3美分,一個可以具有3個* 1C硬幣( ((0.01, 3),)
或一個是1c + 2C( ((0.01, 1), (0.02, 1))
):
{0: {()},
0.01: {((0.01, 1),)},
0.02: {((0.02, 1),), ((0.01, 2),)},
0.03: {((0.01, 3),), ((0.01, 1), (0.02, 1))},
0.04: {((0.02, 2),), ((0.01, 2), (0.02, 1))},
0.05: {((0.01, 1), (0.02, 2)), ((0.05, 1),), ((0.01, 3), (0.02, 1))},
0.06: {((0.02, 3),)},
0.07: {((0.01, 1), (0.02, 3))},
0.08: {((0.01, 2), (0.02, 3))},
0.09: {((0.01, 3), (0.02, 3))},
0.1: {((0.01, 3), (0.02, 1), (0.05, 1)), ((0.01, 2), (0.02, 4))},
0.11: {((0.01, 3), (0.02, 4))},
0.12: {((0.01, 3), (0.02, 2), (0.05, 1))},
0.13: {((0.01, 2), (0.02, 3), (0.05, 1)), ((0.02, 4), (0.05, 1))},
0.14: {((0.01, 1), (0.02, 4), (0.05, 1)), ((0.01, 3), (0.02, 3), (0.05, 1))},
0.15: {((0.01, 2), (0.02, 4), (0.05, 1))}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.