1

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?

Ayam Chan
  • 75
  • 7
  • The recursive approach has a list as an argument, so it's arguments not hashable. How are you using memoization with it? – DarrylG May 11 '20 at 13:10
  • 1
    If you want the answer to explain why the memoization-version of your recursive solution is still slow compared to the iterative solution, then please provide the code for it. – trincot May 11 '20 at 14:30
  • Edited to include memoisation. – Ayam Chan May 11 '20 at 15:05
  • Your memoization involves stringifying the array. That is very expensive. Additionally recursion is relatively slow in Python. – btilly May 11 '20 at 16:15
  • I was able to perform memoization without stringifying the array (slightly modified recursive solution), but it's still much slower. Other posts suggest that recursive memoization solutions should be comparable in speed to iterative dp solutions built on a table--so a bit baffling. – DarrylG May 11 '20 at 18:18

0 Answers0