Home > Software engineering >  Explain how this recursion to get the number of letters in a string works
Explain how this recursion to get the number of letters in a string works

Time:04-10

def funk(someString):
    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
    if someString == "":
        return 0
    elif someString[0] in letters :
        return 1   funk(someString[1:])
    else:
        return 0   funk(someString[1:])
        
someString="3joe3"

print(funk(someString))

It is a function to count all the letters in a string.

So we define allowed characters in the letters.

We define our string and we call the function.

In this example it will first execute the else: part because the first element is a number.

Then it will execute the elif: the part where it goes from the left as it contains the allowed characters and move from there.

My question is where does the number of characters in a string get saved?

CodePudding user response:

according to the function you presented, it uses the recursion feature where it calls the same function within itself. As the function is called it adds the return to the other consequents:

return 1   funk(someString[1:])

After this recursion perceive through the:

if someString == "":

She finished and returned the sum of all the "Returns" she was adding. below is an example of how to store the final value or what you called "number of characters"

def funk(someString):
    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
    if someString == "":
        return 0
    elif someString[0] in letters :
        return 1   funk(someString[1:])
    else:
        return 0   funk(someString[1:])

qtd = funk("HELLO JOAO")

print(qtd)

CodePudding user response:

A recursive function is a special case of a function calling itself. This concept is often very hard for first-time programmer to grasp.

The return value in your case is the same as if we were to invent a non-recursive example where the value being returned is contained in expressions:

def f():
    return 0

def g():
    return 1   f()

def h():
    return 2   g()

print(h())

Output:

3

So, nowhere in the program can we see where the value being calculated is assigned to a variable.

Python, just like other programming languages makes a hidden variable to refer to the return value.

  • Related