Recursive thinking (drilled a dead end)

Recursive thinking: function call the function with a return value

Classic Case:

Quick Index

purpose:

Integer powers of evaluation of clever algorithms

Specifications:

Recursive calculation method of reducing the calculated integer power

The integral power of algorithms: a ** 4 = axaxaxa may be written as a ** 4 = (a ** 2) x (a ** 2), if it is an odd power of: a ** 5 = (a ** 2 ) x (a ** 2) xa

We can use this relationship as the basis of a recursive function: just need to find a suitable basic situation. note,

Computing power necessary to calculate the n-th power of two smaller (n // 2). If we continue to use smaller and smaller the value of n, it eventually reaches 0 (1 // 2 = 0 in the integer division).

As you learned from math class, for any value of a (except 0), a0 = 1. This is the basic situation.

design:

Create function: recPower, need to enter the number of integral powers (s, n) exponentiation of an integer, and the seek

Determining if n is 0 then a direct return

Recursive function (function for each resolution calcd for the final calculation of integral powers) is calculated for each value and returns to the recursion factor

Analyzing odd and even, if odd algorithm factor * factor * a, if an even number: factor * factor

Code:

def recPower(s,n):

  if n==0:

    return 1

  else;

    factor=recPower(s,n//2)

    if n%2 == 0:

      return factor*factor

    else:

      return factor*factor

Dead end problem: Each function returns a value where were we?

Recursion: factor = recPower (2,4 // 2) [factor = 4] - "recPower (2,2 // 2) [factor = 2] -" recPower (2,1 // 2) [factor = 1]

Dead end Answer: Every time the return value is factor, factor is calculated four times

 

 

 

    

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/zhifeiji822/p/11896532.html