Python algorithm problem - recursion (1)

what is recursion

Recursion is a method of solving a problem by breaking it down into smaller sub-problems until you get a problem small enough to be solved easily. Usually recursion involves a function calling itself. Recursion allows us to write elegant solutions to problems that can be difficult to program.


Let's look at the simplest example, summing. For a list to be summed, it is commonly written like this:

def listsum(numlist):
    thesum = 0
    for i in numlist:
        thesum = thesum + i
    return thesum
l = [1,3,5,7,9,]
print listsum(l)

This way of writing is actually very simple. It is a way of adding thesum as an accumulator, and let's see how the superposition looks like.

def listsum1(numlist):
    if len(numlist) == 1:
        return numlist[0]
    else:
        return numlist[0] + listsum(numlist[1:])
    
print listsum1(l)

My understanding is that it is originally a list addition, and the list addition is decomposed into two additions, and then continuously decomposed. The legend can be like this

Look at this again, convert a decimal integer to an N-ary string. In fact, it is similar to superposition, the code is as follows:

def toStr(n,base):
    """

    :param n: integer to convert
    :param base: base to convert
    :return: returns a
    """
    convertString = "0123456789ABCDEF"

    if  n < base:
        return convertString[n]
    else:
        return toStr(n/base,base) + convertString[ n%base]

print toStr(10,2)


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324801042&siteId=291194637