You should use a for
loop rather than a while
loop to solve the problem.
This is as you're just re-writing a for loop.
Using a for loop you can change the loop to a comprehension, and take the sum
of it.
This allows you to get the code:
def simplex(n, dim):
if dim == 1:
return n
dim -= 1
return sum(simplex(i, dim) for i in range(1, n + 1))
However this can be simplified.
When dim is the bullet point the function is:
- \$n\$
- \$\Sigma_{i = 1}^{n} i\$
\$= \frac{n(n + 1)}{2}\$
- \$\Sigma_{i = 1}^{n} (\Sigma_{j = 1}^{i} j)\$
\$= \frac{n(n + 1)(n + 2)}{6}\$
- \$\Sigma_{i = 1}^{n} (\Sigma_{j = 1}^{i} (\Sigma_{k = 1}^{j} k)))\$
\$= \frac{n(n + 1)(n + 2)(n + 3)}{24}\$
- \$\Sigma_{i = 1}^{n} (\Sigma_{j = 1}^{i} (\Sigma_{k = 1}^{j} (\Sigma_{l = 1}^{k} l))))\$
\$= \frac{n(n + 1)(n + 2)(n + 3)(n + 4)}{120}\$
Since we're getting a pattern, we know that the top part of the fraction is:
\$\Pi_{i = 0}^{dim - 1} n + i\$
And if we use oeis to find the denominator it says it's probably the factorial sequence.
And so it's likely:
\$\frac{\Pi_{i = 0}^{dim - 1} n + i}{dim!}\$
This is actually really easy to write in Python.
And so you can get a significant speed up.
from functools import reduce
from math import factorial
from operator import mul
def simplex(n, dim):
return reduce(mul, (n + i for i in range(dim))) // factorial(dim)