[英]How to generate a list of all possible alphabetical combinations based on an input of numbers
[英]Generate a percent of all possible combinations from a list of numbers
我知道itertools.combinations(iterable, r)
返回元素列表/元組的組合(作為可迭代對象)。 如何圍繞它構建一個僅返回所有組合的 x% 的函數? (我只需要一個元組列表,所以它不必是迭代器)。 我希望如果有很少的組合,例如 nCn,它應該返回所有(在這種情況下是一個)(因此最少為 1)。
使用itertools.islice
您可以生成具有元素數量上限的迭代器:
import itertools
MAX_COMBS = 2
combs = itertools.combinations(range(3), 2)
combs_slice = itertools.islice(combs, MAX_COMBS)
print(*combs_slice, sep='\n')
# (0, 1)
# (0, 2)
如果迭代的大小有一個len
,那么你可以根據組合的總數來設置上限:
import itertools
import math
# Percentage of combinations to draw
COMB_RATIO = 0.2
# Lower bound for number of combinations
MIN_COMBS = 2
iterable = range(5)
k = 3
combs = itertools.combinations(iterable, k)
max_combs = max(round(COMB_RATIO * math.comb(len(iterable), k)), MIN_COMBS)
combs_slice = itertools.islice(combs, max_combs)
print(*combs_slice, sep='\n')
# (0, 1, 2)
# (0, 1, 3)
# (0, 1, 4)
iterable = range(3)
k = 2
combs = itertools.combinations(iterable, k)
max_combs = max(round(COMB_RATIO * math.comb(len(iterable), k)), MIN_COMBS)
combs_slice = itertools.islice(combs, max_combs)
print(*combs_slice, sep='\n')
# (0, 1)
# (0, 2)
注意: math.comb
是在 Python 3.8 中引入的,如果您在以前的版本中,您可能需要推出自己的實現,或者從 SciPy 等獲取它。
因為迭代器不攜帶它們的集合有多長的信息,所以你不能從中獲取長度。
在您的情況下,您可以使用公式 n!/(k! (nk)!) 確定組合的大小並迭代直到您的百分比。
例如:
from math import factorial, ceil
def my_combinations():
ratio = .2 # 20 percent
a = range(10)
n = len(a)
k = 5
it = itertools.combinations(a, k)
total_combinations = factorial(n) / factorial(k) / factorial(n-k)
for _ in range(ceil(total_combinations * ratio)):
yield it.next()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.