Partitions of an integer and filtering by number of elements I have Python code to get the partitions of an integer and then display those who have a certain number of elements. The problem is, the program is rather slow and takes a considerable amount of time to complete the partitions of numbers beyond 25. I am certain my algorithm is not optimal and would like to know how to improve it.

#Function to create a partition, receives the integer n
def particion(n):
    if n == 1:
        return [[1]]

#Add the number itself to the results
    res = [[n]]

#Go through all the numbers
    for i in range(1, n):
        a = n-i
        R = particion(i)
    #Add the results of the recursion
        for r in R:
            if r[0] &lt;= a:
                res.append([a] + r)

    return res

#Only print the partitions of length x
resultado=particion(n)
for i in range(0,len(resultado)):
    if len(resultado[i])==x:
        print(resultado[i])
First a technical note.  In mathematics, 2+3 is the same partition as 3+2.  The right name for what you are looking for are combinations.

That said, you are spending most of your time coming up with answers that you will throw away.  Don't.  Spend it coming up with answers that you won't throw away.  Like this:

def compositions(n, size):
    if n == 0 and size == 0:
        yield []
    elif 0 &lt; size:
        for i in range(1, n-size+2):
            for c in compositions(n-i, size-1):
                yield c + [i]

for c in compositions(25, 2):
    print(c)


Update

Since you actually do want partitions, here is an equivalent approach for partitions.

def partitions(n, size, limit=None):
    if limit is None:
        limit = n
    if n == 0 and size == 0:
        yield []
    elif size * limit &lt; n:
        # No solutions possible.
        pass
    elif 0 &lt; size:
        for i in range(1, min(limit, n-size+1)+1):
            for c in partitions(n-i, size-1, i):
                yield [i] + [c]