D = {}

def P(n, s, x):
    if n > s * x or x <= 0:
        return 0
if n == s * x:
    return 1
if (n, s, x) not in D:
    D[n, s, x] = sum(P(n - i * x, s - i, x - 1) for i in range(s))
return D[n, s, x]
An algorithm for randomly generating integer partitions of a particular length, in Python?