如何计算1到N范围内的所有可能组合的数量? [英] How to calculate the number of all possible combinations for a range of numbers from 1 to N?

查看:177
本文介绍了如何计算1到N范围内的所有可能组合的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了执行以下操作:

from itertools import combinations
def brute_force(x):
    for l in range (1,len(x)+1):
        for f in list(combinations(range(0,len(x)),l)):
            yield f
x = range(1,18)
len(list(brute_force(x)))

[out]:

131071




  • 我如何数学计算所有可能组合的数量?

    是否可以在不枚举可能的组合的情况下进行计算呢?

    推荐答案

    总是存在 2 n -1 个集合 {1,的非空子集。 ..,n}

    例如,考虑列表 ['a','b','c ']

    >>> [list(combinations(['a','b','c'],i)) for i in range(1,4)]
    [[('a',), ('b',), ('c',)], [('a', 'b'), ('a', 'c'), ('b', 'c')], [('a', 'b', 'c')]]
    >>> l=[list(combinations(['a','b','c'],i)) for i in range(1,4)]
    >>> sum(map(len,l))
    7
    

    我们列表的长度是3,所以我们有2 3 -1 = 7个组合。

    That the length of our list is 3 so we have 23-1=7 combinations.

    ,并且范围为(10)

    >>> l=[list(combinations(range(10),i)) for i in range(1,11)]
    >>> sum(map(len,l))
    1023      #2^10-1 = 1024-1=1023
    

    请注意,如果要计算空子集,可以使用 2 ^ n

    Note if you want to count the empty subset you can just use 2^n.

    实际上是从数学角度来看:

    Actually at a mathematical perspective :


    集合的k组合是S的k个不同元素的子集。如果集合具有n元素,则k组合的数量等于二项式系数

    并用于所有组合:

    这篇关于如何计算1到N范围内的所有可能组合的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆