问题
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?
来源:https://stackoverflow.com/questions/59437588/implement-number-of-digits-recursively-in-python