python递归

来源:互联网 发布:网络棋牌排行榜 编辑:程序博客网 时间:2024/05/01 02:13
  • 什么是递归?
    函数在定义中直接或者间接的调用自身。

  • 递归的条件
    1.子问题需和原始问题的解决方法相同。调用函数的参数需有规律。
    2.必须有一个明确结束递归的条件。

  • 典型的递归实例
    1.斐波纳契数列:(1,1,2,3,5,8……)

#python递归实现def Fib(index):    if index == 0 or index == 1:        retrun 1    else:        result = Fib(index-1)+Fib(index-2)    return result#非递归,列表形式输出def Fib(len):    fib = [1,1]    for i in range(len-2):        fib.append(fib[-2]+fib[-1])    print fib#迭代器实现 def fab(max):     n, a, b = 0, 0, 1     while n < max:         yield b         a, b = b, a + b         n = n + 1 >>> for n in fab(5):  ...     print n  ...  1  1  2  3  5

2.汉诺塔

#只有一个盘子的时候,直接从A-C#n个盘子时,需先将n-1个借助C从A-B,然后将第n个盘移到C,再将n-1借助A从B-Cclass Hanoi():    def __init__(self,count):        self.count = 0    def move(self,num,src,to):        self.count = self.count + 1        print (u"第%s步:%s号从%s到%s") % (self.count,num,src,to)    def Planet(self,n,src,denpend,to):        if n == 1:            self.move(1,src,to)        else:            self.Planet(n-1,src,to,denpend)            self.move(n,src,to)            self.Planet(n-1,denpend,src,to)if __name__ == '__main__':    n = int(raw_input("The number of Planet:"))    print (u"注意,我要开始移动盘子了!")    han = Hanoi(0)    han.Planet(n,"A",'B','C')

3.求n个自然数的最大公约数与最小公倍数

#两个数的公约数def gcd(a,b):    if b == 0:        return a    return gcd(b,a % b)#利用公约数,求公倍数。公倍数=a*b/公约数def lcn(a,b):    x = gcd(a,b)    return a*b/x#列表循环def gcdN(num_ls):    nlen = len(num_ls)    if nlen < 0:        return -1    if (nlen == 1):        return num_ls[0]    nRes = gcd(num_ls[0],num_ls[1])    i = 2    while i<nlen:        nRes = gcd(nRes,num_ls[i])        i += 1    return nResdef lcnN(num_ls):    nlen =len(num_ls)    if nlen < 0:        return -1    if nlen == -1:        return num_ls[0]    nRes = lcn(num_ls[0],num_ls[1])    i = 2    while  i < nlen:        nRes = lcn(nRes,num_ls[i])        i += 1    return nRes这里写代码片

4.快速排序

def Quicksort(ls,start,end):    i = start    j = end    if i >= j:#需进行判断,否则将一直递归下去        return    key = ls[i]    while i < j:        while i < j and ls[j] >= key:            j = j - 1        if i < j:            ls[i]=ls[j]            i = i + 1        while i < j and ls[i] <= key:            i = i + 1        if i < j:            ls[j]=ls[i]            j = j - 1    ls[i] = key    Quciksort(ls,start,i-1)    Quicksort(ls,j+1,end)    return ls    '''    快速排序理解:    1.选取基准值,一般取列表中第一个元素。取i和j分别为列表开始和结束位置    2.取出基准值元素,放入key3.从列表最后的位置j开始向前遍历,遇到小于key的值,放入i位置上。    4.从i+1的位置开始向后遍历,遇到大于key的值,放入j位置,此时可j+1,使下次遍历跳过j位置    5.循环,直到i=j,此时将key值赋值给ls[i],此时,基准值左边为小于其的值,右边有大于其的值。    6.左右两个列表继续重复以上操作。直到区间只剩一个值。
0 0
原创粉丝点击