Paul Hashmi
Paul Hashmi

Reputation: 466

Is this recursive?

Second attempt here, I just wanted to know if this is considered a recursive function.

The purpose of the function is to take a string and if the the first element is equal to the last element then append the last element to a list and return nothing, else call istelf and pass the same string from index [1] finally append the first element to the list

I know that error checking needs to be done on the if statement. However I am only doing this to try and get my head around recursion...Struggling to be honest.

Also I would never write a program like this if it where anything but trivial I just wanted to check if my understanding is correct so far.

def parse(theList):
    theList.reverse()
    parsedString = ''.join(theList)
    return parsedString




def recursiveMessage(theString):

    lastElement = theString[len(theString) - 1]

    if theString[0] == lastElement:
        buildString.append(theString[0])
        return None
    else:
        recursiveMessage(theString[1::])

    buildString.append(theString[0])





toPrint = "Hello Everyone!"
buildString = []   
recursiveMessage(toPrint)
print(parse(buildString))

Thanks again.

Upvotes: 3

Views: 65

Answers (1)

Chris
Chris

Reputation: 22953

Is this recursive?

If at any point in a function's execution it calls itself, then it is consider recursive. This happens in your example, so recursiveMessage is indeed recursive.

so which is quicker recursion or iteration?

Recursion is usually much slower and consumes more space due to a new stack frame having to be created on the call stack each recursive call. If you know your recursive function will need to be run many times, iteration is the best route.

As an interesting side note, many compilers actually optimize a recursive function by rolling it out into a loop anyways.

Upvotes: 2

Related Questions