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)
import itertools
from functools import reduce
elements = {"A": 1, "B": 2, "C": 1}
sum_restriction = lambda x: sum(elements[i] for i in x)==4
max_els = 4 // min(elements.values()) + 1
res = reduce(lambda x,y:x+y,[list(filter(sum_restriction, itertools.combinations_with_replacement(elements.keys(), i))) for i in range(max_els+1)])
你要找的不是排列,而是组合。置换是在不重复的情况下重新排列有限的元素集,而组合是假定
n
元素之一的m
字段中的每一个,在python中用itertools.computations_with_replacement
表示。在代码方面:我的示例返回:
相关问题 更多 >
编程相关推荐