擅长:python、mysql、java
<pre><code>from itertools import permutations, chain
def get_permutations_count_to_n(item_dict, n, max_items=4):
""" For a given dict with items as keys and weights as values, return a set of permutations that have a combined weight of N
:param item_dict: dictionary with items as keys and their weight as value
:param n: integer that should be the combined weight of permutated items
:param max_items: the maximum number of items that may occur in a permutation """
item_list = list(items.keys()) * max_items
combs = [list(permutations(item_list, i)) for i in range(1, max_items+1)]
filtered_combs = [comb for comb in chain.from_iterable(combs) if sum(item_dict[x] for x in comb) == n]
return set(filtered_combs)
items = {'A': 1, 'B': 2}
get_permutations_count_to_n(items, n=4)
</code></pre>
<pre><code>>>> {('B', 'A', 'A'), ('B', 'B'), ('A', 'A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'B', 'A')}
</code></pre>