Search code examples
pythonrecursionpython-3.12

Set Recursion Limit doesn't work in the standalone Python interpretator but works in online interpretators


Python 3.12.5

The algorithm for calculating the value of the function F(n), where n is a natural number, is given
by the following ratios:
F(n) = 1 for n = 1;
F(n) = 2 for n = 2;
F(n) = n * (n - 1) + F(n - 1) + F(n - 2) if n > 2.
What is the value of the expression F(2024) - F(2022) - 2 * F(2021) - F(2020)?

At first I just used recursion with the big limit, but I found out that the program runs TOOOOOOO slow (because I didn't use @lru_cache), I watched a video with the solution of this task and used this code

from functools import lru_cache
import sys
sys.setrecursionlimit(50000000)

@lru_cache
def F(n):
    if n == 1:
        return 1
    if n == 2:
        return 2
    return n*(n-1) + F(n-1) + F(n-2)
print(F(2024) - F(2022) - 2*F(2021) - F(2020))

It worked for the author of the video. When I had tried it in an online interpretator, it worked too and I got the correct answer. But it doesn't work on my PC. I get RecursionError although I set the recursion limit to 50000000:

return n*(n-1) + F(n-1) + F(n-2)
                     ^^^^^^
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

What do I do? Maybe there are some other solutions?


Solution

  • It seems you have bumped into the same bug as reported in issue #112215 - 3.12 setrecursionlimit is ignored in connection with @functools.cache. See also #112282. It looks like a major regression was introduced in 3.12 and is still present in 3.12.5.

    For the actual challenge you try to solve, you don't need a function that calculates Fibonacci-like numbers at all. You can derive the answer by expanding the recursive š¹-terms with greater arguments until we're left with an expression that just has a number of š¹2021 and š¹2020, which happen to cancel each other:

    We start with:

    Ā  Ā  Ā  š¹2024 āˆ’ š¹2022 āˆ’ 2š¹2021 āˆ’ š¹2020

    We can expand that š¹2024:

    Ā  Ā  Ā  2024ā‹…2023 + š¹2023 + š¹2022 āˆ’ š¹2022 āˆ’ 2š¹2021 āˆ’ š¹2020

    We can eliminate š¹2022 āˆ’ š¹2022:

    Ā  Ā  Ā  2024ā‹…2023 + š¹2023 āˆ’ 2š¹2021 āˆ’ š¹2020

    We can expand that š¹2023:

    Ā  Ā  Ā  2024ā‹…2023 + 2023ā‹…2022 + š¹2022 + š¹2021 āˆ’ 2š¹2021 āˆ’ š¹2020

    We can reduce š¹2021 āˆ’ 2š¹2021, to āˆ’ š¹2021:

    Ā  Ā  Ā  2024ā‹…2023 + 2023ā‹…2022 + š¹2022 āˆ’ š¹2021 āˆ’ š¹2020

    We can expand that š¹2022:

    Ā  Ā  Ā  2024ā‹…2023 + 2023ā‹…2022 + 2022ā‹…2021 + š¹2021 + š¹2020 āˆ’ š¹2021 āˆ’ š¹2020

    We can now eliminate all š¹ terms, and so the result is:

    Ā  Ā  Ā  2024ā‹…2023 + 2023ā‹…2022 + 2022ā‹…2021 = 12271520