Question from codewars https://www.codewars.com/kata/52ec24228a515e620b0005ef/python
In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. For example, 4 can be partitioned in five distinct ways:
4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
Given number n, write a function exp_sum(n) that returns the total number of ways n can be partitioned. Eg: exp_sum(4) = 5
Why does the recursion approach:
def exp_sum(n):
arr = list(range(1, n+1))
mem = {}
return rec(n, arr, mem)
def rec(n, arr, mem):
key = str(n)+ ":" + str(arr)
if key in mem:
return mem[key]
elif n < 0:
return 0
elif n == 0:
return 1
elif n > 0 and not arr:
return 0
else:
to_return = rec(n - arr[-1], arr, mem) + rec(n, arr[:-1], mem)
mem[key] = to_return
return to_return
take so much longer to run compared to this particular method (top solution of this kata)?
def exp_sum(n):
if n < 0:
return 0
dp = [1]+[0]*n
for num in range(1,n+1):
for i in range(num,n+1):
dp[i] += dp[i-num]
return dp[-1]
Even with using memoisation, the recursion approach barely managed to pass the test case at a time of about 10000ms, compared to the 1000ms taken for the above approach.
And can anyone explain how the particular method above works and the logic behind it or if it uses some particular algorithm which I can read up about?