A variety of methods to achieve a classic case of Python

Today, we see a classic case, hope that helps

The original question is this:

Suppose you want to calculate power, like built-in functions and operators ** pow had done. To define a number of integer power, there are a variety of ways, but let's look at a simple definition: power (x, n) (n-th power of x) is a digital x multiplied by itself n - 1 times results soon the result of multiplying the n x. In other words, power (2, 3) is the result of 2 raised twice, i.e., 2 × 2 × 2 = 8.

 

method one: 

 1 def funa(x, n):
 2     res = x
 3     if n < 0:
 4         return -1
 5     elif n == 0:
 6         return 1
 7     elif n > 0:
 8         n -= 1
 9         while n > 0:
10             res *= x
11             n -= 1
12         return res
13     else :
14         print("!")

This method is most languages ​​are written, the code redundancy, streamlining is not enough, although the function can be achieved, but not beautiful

Method Two:

1 def funb(x, n):
2     result = 1
3     for i in range(n):
4         result *= x
5     return result

This method is in line with the United States of python

Method three:

1 def func(x, n):
2     if n == 0:
3         return 1
4     else:
5         return x * func(x, n - 1)

This method is recursive, you can understand

Although this example is simple, but the way to achieve a lot, each method has advantages and disadvantages, so we can usually divergent thinking, a variety of solutions to a problem

 

Guess you like

Origin www.cnblogs.com/cy666/p/11067866.html