#!/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