Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a non-recursive function as maximum recursion depth has been exceeded

I was wondering if someone could help me rewrite this code as non-recursive so it can compute higher numbers, my current code looks like this:

def T(n):
    if n < 3:
        return n
    return T(n - 1) + 2 * T(n - 2) - T(n - 3)

The function is designed for the purpose of arithmetic where T(0) = 0, T(1) = 1, T(2) = 2, T(3) = 4, T(5) = 7 etc…

I want to be able to compute values as high as T(1000) for example, I didn’t know if there was a simplistic way to rewrite the code or if it would just be a case of computing the values?
Any help would be appreciated, I’m currently getting the error ‘maximum recursion depth exceeded’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a "rolling" method where you keep track of the last three results and as you add the new result, you also kick the oldest:

def T(n):
    if n < 3:
        return n
    a, b, c = 0, 1, 2
    for i in range(2, n):
        a, b, c = b, c, c + 2*b - a
    return c
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading