python算法习题(二): 递归算法

列举两个经典应用:

1. 斐波那契数列

递归算法实现

def fib1(N):
    if N == 1:
        return 1
    elif N == 2:
        return 1
    else: 
        return fib1(N-1) + fib1(N-2)

不用递归实现:

def fib2(N):
    a = 1
    b = 1
    for i in range(1, N):
        yield a  
        a, b = b, a+b

2. 快速排序

def qsort(a):
    gtl = []
    ltl = []
    if not len(a):
        return []
    elif len(a) == 1:
        return a
    else:
        mid = a[len(a)//2]  # 取中位数
        for i in a:
            if i < mid:
                ltl.append(i)
            if i > mid:
                gtl.append(i)
        return qsort(ltl) + [mid] + qsort(gtl)

顺便贴一下选择排序:

def select_sort(a):
    maxnum = 0
    if len(a) == 1:
        return a
    else:
        for i in a:
            if i > maxnum:
                maxnum = i
        a.remove(maxnum)
        return select_sort(a)+ [maxnum]

你可能感兴趣的:(python,算法学习)