Why does this iterative program exceed recursion limit?

Question:

I’m trying to solve a project Euler question (number 52) which asks for the smallest integer, n, such that n, 2n, 3n, 4n, 5n, 6n all have the same decimal digits permuted. I thought I’d start with a brute force program (as a programming exercise for myself) which looks for an integer n such that n and 2n have the same digits (the project Euler question mentions that 125874 is one such integer, so I figured a brute force program would work). So I wrote a python program that looks at each integer in order, creates a sorted list of its digits, and compares that list against against the sorted list of digits for 2n. My program seems iterative, so I’m not sure why it stops running after a fraction of a second and sends back “maximum recursion depth exceeded in comparison”. I decided to bound the unbounded search in the function “k” below to see how far it got, and it seems to have gotten no higher than n= 100,000. Given that each time it calls k, it only has to sort and compare two lists of size no more than 6, I wonder why it gives me this error? I googled the error and it was suggested to increase the recursion limit, so I added the “sys.setrecursionlimit(2000)” you see.

Here is my code:

The function f takes an integer and returns a list of its digits. g sorts them. h compares the list for n and 2n. and k iterates.

import math
import sys

sys.setrecursionlimit(2000)

def f(n, l):
    if (math.floor(n / 10) == 0):
        l.append(n)
        return l

    else:
        l.append(n % 10)
        return f(int((n - (n % 10)) / 10), l)

def g(n):
    return sorted(f(n, []))

def h(n):
    if ((g(n) == g(2 * n))):
        return 1
    else:
        return 0

def k(n):
    if ((h(n) == 1)):
        return n
    elif ((n <= 100000)):
        return k(n + 1)
    else:
        return "checked up to bound"

print(k(1))
Asked By: user7343674

||

Answers:

Focusing on this part:

def k(n):
    if ((h(n) == 1)):
        return n
    elif ((n <= 100000)):
        return k(n + 1)

125874 is the smallest number for which h(n) == 1, so this recursively calls k(1), k(2), k(3), ... k(125874). sys.setrecursionlimit(2000) cannot help with that. Go through the different values of n iteratively, i.e. with a loop.

Answered By: Alex Hall

I dont know c dd ddfdfhdffjfhfhfbsfhbdsbf

Answered By: Ayan Liaqat
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.