boost the speed of recusrive function

Question:

The function is too slow, or infinite, i didnt get the result. how to fix that?

def x(a):
    return x(a - 1) + x(a - 2) + 42 if a > 1 else a
print(x(195)) 
Asked By: Hahan't

||

Answers:

You can avoid recursion by using a simple for loop as follows:

def x(a: int) -> int:
    if a <= 1:
        return a

    p, q = 0, 1

    for _ in range(2, a + 1):
        p, q = q, p + q + 42

    return q

There you go.

Answered By: WArnold

Use functools.cache to save the results of each call to x().

from functools import cache

@cache
def x(a):
    return x(a - 1) + x(a - 2) + 42 if a > 1 else a

print(x(195))  # 1744559950484785950724677014047127864991062
Answered By: Fractalism
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.