Implement number of digits recursively in Python

别等时光非礼了梦想. 提交于 2021-01-29 18:54:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!