![](/img/trans.png)
[英]Python: Sample N random items from list with weights but without repetition
[英]Distributions without repetition and weights in Python
我想在 Python 中編寫一個程序,可以顯示符合以下條件的所有配置。
給定一組n 個項目及其相應的權重(例如'A': 1, 'B': 2, 'C': 3
)
每個處置的總權重應總和為 x
每個組合都應該由恰好 y 個項目組成
不允許重復
順序無關緊要(即{A, B} = {B, A}
)
例如,給定集合'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5
x = 6 和 y = 2
一種。 {A, E}, {B, D}
是可能的配置,因為它們的總權重總和為 6,它們正好由 2 個項目組成並且沒有重復
b. {A, B, C}
不是可能的配置,因為它由 3 個項目組成
c。 {C, C}
不是可能的配置,因為不允許重復
d. {C, D}
不是可能的配置,因為它們的權重之和不等於 6
e. 即使{A, E}
是一種可能的配置,它也應該只顯示一次,即程序應該顯示{A, E}
或{E, A}
,而不是兩者,因為在這種情況下{A, E} = {E, A}
。
我希望我說得足夠清楚,並提前感謝每個決定閱讀這篇文章的人:)
我嘗試了幾種策略,但它們僅適用於重復排列(即僅滿足條件 1 和 2)。
其中之一是:
def get_permutations_count_to_n(item_dict, n, max_items = 2):
""" 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(max_items, 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, 'C': 3, 'D': 4, 'E': 5}
get_permutations_count_to_n(items, n=6)```
#getting
{('B', 'D'), ('C', 'C'), ('E', 'A'), ('D', 'B'), ('A', 'E')}
這是一個采用“蠻力”方法的快速腳本。
from itertools import combinations
items = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
x = 6
y = 2
result = [list(subset) for subset in combinations(items,y)
if sum(map(items.get,subset)) == x]
腳本運行后的數組結果就是列表
[['A', 'E'], ['B', 'D']]
combinations(items,y)
允許我們遍歷滿足條件 2 和 3 的子列表列表(您稱之為“處置”),使得沒有兩個子列表對應於同一組元素。 我們取其中的每一個並只保留滿足條件 4 的子列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.