Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this function recursive even though it doesn't call itself?

from pythonds.basic.stack import Stack

rStack = Stack()

def toStr(n,base):
    convertString = "0123456789ABCDEF"
    while n > 0:
        if n < base:
            rStack.push(convertString[n])
        else:
            rStack.push(convertString[n % base])
        n = n // base
    res = ""
    while not rStack.isEmpty():
        res = res + str(rStack.pop())
    return res

print(toStr(1345,2))

I'm referring to this tutorial and also pasted the code above. The tutorial says the function is recursive but I don't see a recursive call anywhere, just a while loop. What am I missing?

like image 560
kalin Avatar asked Dec 04 '25 17:12

kalin


1 Answers

You are right that this particular function is not recursive. However, the context is, that on the previous slide there was a recursive function, and in this one they want to show a glimpse of how it behaves internally. They later say:

The previous example [i.e. the one in question - B.] gives us some insight into how Python implements a recursive function call.

So, yes, the title is misleading, it should be rather Expanding a recursive function or Imitating recursive function behavior with a stack or something like this.

One may say that this function employs a recursive approach/strategy in some sense, to the problem being solved, but is not recursive itself.

like image 112
BartoszKP Avatar answered Dec 07 '25 16:12

BartoszKP