1. 程式人生 > >典型遞迴演算法例子-------Python實現

典型遞迴演算法例子-------Python實現

#!/usr/bin/python
#coding=utf-8
'''
Created on 2012-9-25

@author: linzuxin
'''

status = {}

def factorial(n):
    '''
            輸入一個數字,求其階乘。status是一個hash,用來儲存中間結果,避免重複計算
    @param n: 要求的數字
    @return: n的階乘 
    '''
    if n == 0 or n == 1:
        status[0] = 1
        status[1] = 1
        return 1
    elif status.has_key(n):
        return status[n]
    else:
        status[n] = factorial(n - 1) * n
        return status[n] 
    
print factorial(100)

#!/usr/bin/python
#coding=utf-8
'''
Created on 2012-9-25

@author: linzuxin
'''
status = {}

def fibonacci(n):
    '''
            輸入一個數字,求其斐波那契數。status是一個hash,用來儲存中間結果,避免重複計算
    @param n: 要求的數字
    @return: n的斐波那契數 
    '''
    if n == 0 or n == 1:
        status[0] = 1
        status[1] = 1
        return 1
    elif status.has_key(n):
        return status[n]
    else:
        status[n] = fibonacci(n - 2) + fibonacci(n - 1)
        return status[n]

print fibonacci(100)


#!/usr/bin/python
#coding=utf-8
'''
Created on 2012-9-26

@author: linzuxin
'''
def permutation(array, start, end):
    '''
            輸入一個數組,然後輸出其全排列
    @param array: 要求全排列的陣列
    @param start: 陣列的開始下標 
    @param end: 陣列的結束下標
    '''
    if start == end:
        for i in array:
            print i,
            
        print
    else:
        for i in range(start, end + 1):
            array[start], array[i] = array[i], array[start]
            permutation(array, start + 1, end)
            array[start], array[i] = array[i], array[start]

array = [1, 2, 3]            
permutation(array, 0, len(array) - 1)
#!/usr/bin/python
#coding=utf-8
'''
Created on 2012-9-26

@author: linzuxin
'''
status = {}

def divideInt(n, m):
    '''
            輸入一個數字,求其整數劃分種類
    @param n: 要求的數字
    @param m: 劃分中最大的加數不大於m
    @return: 劃分總數
    '''
    try:
        return status[(n, m)]
    except KeyError:
        if n == 1 or m == 1:
            status[(n, m)] = 1
            return status[(n, m)]
        elif m > n:
            status[(n, m)] = divideInt(n, n)
            return status[(n, m)]
        elif m == n:
            status[(n, m)] = 1 + divideInt(n, n - 1)
            return status[(n, m)]
        else:
            status[(n, m)] = divideInt(n - m, m) + divideInt(n, m - 1)
            return status[(n, m)]
    
print divideInt(500, 500)

#!/usr/bin/python
#coding=utf-8
'''
Created on 2012-9-26

@author: linzuxin
'''

count = 0
def hanoi(n, start, end, middle):
    '''
            輸入漢諾塔個數,求出其需要移動的次數
    @param start: 開始漢諾塔的位置
    @param end: 最終漢諾塔的位置
    @param middle: 用來過渡的位置
    '''
    global count
    if n == 1:
        print start, ' => ', end
        count += 1
    else:
        hanoi(n - 1, start, middle, end)
        print start, ' => ', end
        count += 1
        hanoi(n - 1, middle, end, start) 
        
hanoi(2, 'A', 'B', 'C')
print count