python函数递归的几个例子
2016-10-27 15:45
405 查看
斐波那契数列1,1,2,3,5,8,13,21……
#!/usr/bin/env python
# encoding: utf-8
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
print fib(6)
汉诺塔
#!/usr/bin/env python
# encoding: utf-8
count = 0
def hanoi(n,a='左',b='中',c="右"):
global count
if n == 1:
format = 'Move %3d from % 5s to % 5s count:%i'
count += 1
print format % (n,a,c,count)
else:
hanoi(n-1,a,c,b)
format = 'Move %3d from % 5s to % 5s count:%i'
count +=1
print format % (n,a,c,count)
hanoi(n-1,b,a,c)
hanoi(4)
回文数
def is_panlindrom_rec(arg):
if len(arg) <=1:
return True
else:
if arg[0] != arg[-1]
return False
else:
return is_panlindrom_rec(arg[1:-1])
阶乘
def p(n):
if n == 1 or n == 0:
return 1
else:
return n * p(n-1)
随机停车
#!/usr/bin/env python
# encoding: utf-8
import random
def parking(low,high):
if high - low < 1:
return 0
else:
x = random.uniform(low,high-1)
return 1 + parking(low,x) \
+ parking(x+1,high)
print parking(0,9)
#!/usr/bin/env python
# encoding: utf-8
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
print fib(6)
汉诺塔
#!/usr/bin/env python
# encoding: utf-8
count = 0
def hanoi(n,a='左',b='中',c="右"):
global count
if n == 1:
format = 'Move %3d from % 5s to % 5s count:%i'
count += 1
print format % (n,a,c,count)
else:
hanoi(n-1,a,c,b)
format = 'Move %3d from % 5s to % 5s count:%i'
count +=1
print format % (n,a,c,count)
hanoi(n-1,b,a,c)
hanoi(4)
回文数
def is_panlindrom_rec(arg):
if len(arg) <=1:
return True
else:
if arg[0] != arg[-1]
return False
else:
return is_panlindrom_rec(arg[1:-1])
阶乘
def p(n):
if n == 1 or n == 0:
return 1
else:
return n * p(n-1)
随机停车
#!/usr/bin/env python
# encoding: utf-8
import random
def parking(low,high):
if high - low < 1:
return 0
else:
x = random.uniform(low,high-1)
return 1 + parking(low,x) \
+ parking(x+1,high)
print parking(0,9)
相关文章推荐
- 最近正准备找工作呢,熟悉下递归算法,做了几个递归的例子包括汉诺塔问题
- sqlserver实现oracle递归树函数例子(start with.....connect by prior.....)
- python 使用函数装饰器的例子
- sql server实现oracle递归树函数例子(start with.....connect by prior.....)
- 关于C++虚继承、虚函数继承的几个例子
- 关于java中servlet中的路径的几个函数的例子
- Python中几个挺好用的东西(函数、类、装饰器)
- Python与 PHP使用递归建立多层目录函数
- 爱上python(几个小例子)
- python小例子之1 -- 递归遍历目录
- python的几个内建函数:apply(),filter(),map(),reduce(
- python 算法的优化及几个基本函数
- Python OS几个主要函数
- 几个 CGRect 函数例子
- python的几个内建函数:apply(),filter(),map(),reduce()
- python小例子之1 -- 递归遍历目录
- python-Levenshtein几个计算字串相似度的函数解析
- python几个有意思的函数
- python操作时间的几个重要函数总结 import time!
- python几个时间函数