递推
递归
- 阶乘
def factorial(n):
if n == 1:
return n
return n*factorial(n-1)
- 斐波那契数列
def FibonacciSeq(n):
if n == 0:
return n
elif n == 1:
return n
elif n > 1:
return FibonacciSeq(n-1) + FibonacciSeq(n-2)
- 最大公约数
def find_divisor(a,b):
bigone = 0
smallone = 0
if a < b:
bigone = b
smallone = a
else:
bigone = a
smallone = b
if bigone % smallone == 0:
return smallone
else:
return find_divisor(smallone,bigone%smallone)
- 数组求和
def sumfuc(alist):
if not alist:
return 0
a = alist.pop()
return a + sumfuc(alist)
- 反转字符串
def str_reverse(astr):
if not astr:
return ''
elif len(astr) == 1:
return astr
return str_reverse(astr[1:]) + astr[0]
- 插入排序
#插入排序(递归实现):
def insertSort(alist):
if len(alist) == 1:
return alist
alist[:-1] = insertSort(alist[:-1])
done = False
passnum = alist[-1]
idx = len(alist) - 1
while idx > 0 and alist[idx-1] > passnum:#注意idx表示passnum的位置
alist[idx] = alist[idx-1]
idx -= 1
alist[idx] = passnum
return alist
- 集合的划分
#集合的划分
def divideset(n,k):
if n < k or k <= 0:
return 0
elif n == k or n == 1 or k == 1:
return 1
return divideset(n-1,k) * k + divideset(n-1,k-1)
- 放苹果
#放苹果
def divideapple(m,n):
if m < 0 or n <= 0:
return 0
elif m ==0 or n == 1:
return 1
elif m < n:
return divideapple(m,m)
elif m >= n:
return divideapple(m,n-1) + divideapple(m-n,n)
- 猴子吃桃
猴子吃桃问题:
猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个,第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘多少个桃子?答案为:1534个。
#猴子吃桃
def MonkeyEatsPeach(n,day):
if day == 1:
return n
n = (n + 1) * 2
return MonkeyEatsPeach(n,day-1)
- 汉诺塔问题
#汉诺塔
def HanoTower(n,a,b,c):
if n == 1:
print("{}-->{}".format(a,c))
return None#注意这里要有return(结束函数条件)
HanoTower(n-1,a,c,b)
print("{}-->{}".format(a,c))
HanoTower(n-1,b,a,c)
HanoTower(3,'A','B','C')
输出
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C
- 数的计数(Noip2001)
#数的计数
def passnum(n):
if n // 2 == 1:#注意这里是=1
return 1
a = n // 2
return a + a*passnum(a)
- 逆波兰表达式
#逆波兰表达式
#数字必须<10
def ReversePolishNotation(exp):
from pythonds.basic import Stack
s = Stack()
for x in exp[::-1]:
if x in '+-*/':
a = s.pop()
b = s.pop()
c = eval(a+x+b)
s.push(str(c))#注意这里是str(c),不然读出来的a就是整数
else:
s.push(x)
return s.pop()
- 全排列
#全排列
def permutation(astr):
n = len(astr)
if n <= 1:
return astr
result = []
for i in range(n):
restperm = permutation(astr[:i] + astr[i+1:])
for x in restperm:
result.append(astr[i]+x)
return result
- 分解因数
#分解因数
def factorization(n):
return factorizationHelper(2,n)
def factorizationHelper(begin,n):#从begin开始进行分解因式
factor = 1#因数初始值为1,指数字本身
if n == 2:#递归结束条件
return 1
import math
if begin < math.ceil(n**0.5):#从begin,到<n^0.5为止
for x in range(begin,math.ceil(n**0.5)):#n/x > x
if n % x == 0:
factor += factorizationHelper(x,n//x)#return --> int
return factor