0

This is really similar to Fibonacci Sequence problem. I understand the DP optimization with Fibonacci function using the for loop, but I'm having hard time to connect to this problem.

The recursion function I want to optimize is:

def cal(n): if n <= 0: return 1 else: return cal(n-25)+cal(n-26)

4
  • from itertools import lru_cache then add @lru_cache decorator before your function. all done ✅ Commented Oct 1, 2022 at 21:55
  • Can you please write the code out? Commented Oct 1, 2022 at 23:16
  • line 1) from itertools... line 2) @lru_cache, line 3) def cal(n): ..., line 4) print(cal(some_number)) Commented Oct 2, 2022 at 14:08
  • @underflow - can you show us a few expected outputs? Commented Oct 2, 2022 at 20:21

2 Answers 2

1

Something like this may help:

(It's inspired by previous post)


from functools import cache

@cache
def cal(n):
    if n <= 0:
        return 1
    else:
        return cal(n-25) + cal(n-26)



print(cal(100))
Sign up to request clarification or add additional context in comments.

Comments

0

The idea of a "for loop optimization" is that we calculate cal(0), cal(1), cal(2), ... consecutively. And when we want cal(n), we already have cal(n-25) and cal(n-26) stored in an array.

So, the following solution has linear complexity for non-negative n:

def cal(n):
    mem = [1]  # cal(0) is 1
    for i in range(1, n + 1):
        num = 1 if i - 25 < 0 else mem[i - 25]
        num += 1 if i - 26 < 0 else mem[i - 26]
        mem.append (num)
    return mem[-1]

One can further optimize to make all the values cal(1), cal(2), ..., cal(n) globally available after calculating the last of them.

2 Comments

Try it with cal(100) or cal(10) both got this - IndexError: list index out of range?
It's well explained and working perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.