开发者社区 问答 正文

从数字列表中生成所有可能组合的百分比

我知道itertools.combinations(iterable,r)返回元素列表/元组的组合(作为iterable)。如何围绕它构建仅返回所有组合的x%的函数?(我只需要一个元组列表,因此它不必是迭代器)。我希望如果组合很少,例如nCn,则应返回所有组合(在这种情况下为一种)(因此最少为1)。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-25 09:18:45 2707 分享 版权
1 条回答
写回答
取消 提交回答
  • 使用itertools.islice可以生成一个迭代器,其元素数量上限:

    import itertools
    
    MAX_COMBS = 2
    combs = itertools.combinations(range(3), 2)
    combs_slice = itertools.islice(combs, MAX_COMBS)
    print(\*ombs_slice, sep='\n')
    # (0, 1)
    # (0, 2)
    

    如果iterable的大小为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(\*ombs_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(\*ombs_slice, sep='\n')
    # (0, 1)
    # (0, 2)
    

    注意:math.comb是Python 3.8中引入的,如果您使用的是以前的版本,则可能需要滚动自己的实现或从SciPy获得它。

    回答来源:stackoverflow

    2020-03-25 09:18:54
    赞同 展开评论
问答地址: