0

I have this code to print the numbers based on the number of digits inputted (for example printNum1(2) will output 10-99, printNum1(3) will output 100-999, printNum1(4) will output 1000-9999) iteratively in python:

from time import time
def printNum1(n):
    start = time()
    y = 10 ** n
    x = y//10

    for i in range(x, y):
        print(i)
    print(f"For number {n}\nSol took: {time() - start} seconds")
printNum1(5)

I am trying to implement it recursively now for practice:

from time import time
from sys import setrecursionlimit
class PrintNumRec:
    setrecursionlimit(1000000000)
    def rec(self, x, y):
        if x == y:
            return
        else:
            print(x)
            return self.rec(x + 1, y)

    @staticmethod
    def init(n):
        start = time()

        y = 10 ** n
        x = y//10

        self = PrintNumRec()
        PrintNumRec.rec(self, x, y)
        print(f"For number {n}\nRecursive took: {time() - start} seconds")


PrintNumRec.init(10)

Originally I was getting:

RecursionError: maximum recursion depth exceeded while calling a Python object

I have seen this post What is the maximum recursion depth in Python, and how to increase it?

From this post I tried to set the recursion limit higher but my program freezes for any number higher than 4 and I get this:

Process finished with exit code -1073741571 (0xC00000FD)

Is there any way to implement this recursively in Python or should I just stick to the iterative way?

BpY
  • 403
  • 5
  • 12
  • 1
    The iterative method is going to be faster and easier. The range is easily calculated as `10 ** (n-1)` to `10 ** n - 1` so constantly calculating `x + 1` and checking `x == y` on each recursive call will be very slow. – N Chauhan Dec 21 '19 at 15:52
  • Usually when you get a recursion error it means that you have an infinite recursion. Try tracking a variable by printing it to see if the number makes sense. – Yacine Mahdid Dec 21 '19 at 16:16
  • @YacineMahdid I went through the debugger and it works fine, no errors but doing this for 1000's numbers defeats the purpose. – BpY Dec 21 '19 at 16:24

0 Answers0