迭代和递归(Python)--乘方、最大公约数、汉诺塔、斐波那契、回文字符串
2015-07-23 15:24
771 查看
1.迭代
运行结果:
2.递归的乘法运算:
运行结果:
3.递归乘方:
运行结果:
4.最大公约数:
迭代法:
运行结果:
递归:
运行结果:
5.汉诺塔:
运行结果:
6.斐波那契数
运行结果:
7.回文字符串:
运行结果:
来自MIT的MOOC课件
def iterPower(base,exp): result=1.0 while exp>0: result*=base exp-=1 return result
运行结果:
2.递归的乘法运算:
def recurMul(a,b): if b==1: return a else: return a+recurMul(a,b-1)
运行结果:
3.递归乘方:
def recurPowerNew(base,exp): if exp==0: return 1 elif exp>0 and exp%2==0: return recurPowerNew(base*base,exp/2) else: return base*recurPowerNew(base,exp-1)
运行结果:
4.最大公约数:
迭代法:
def gcdIter(a,b): r=1 while r!=0: r=a%b a=b b=r return a
运行结果:
递归:
def gcdRecur(a,b): if b==0: return a else: return gcdRecur(b,a%b)
运行结果:
5.汉诺塔:
def printMove(fr, to): print('move from ' + str(fr) + ' to ' + str(to)) def Towers(n, fr, to, spare): if n == 1: printMove(fr, to) else: Towers(n-1, fr, spare, to) Towers(1, fr, to, spare) Towers(n-1, spare, to, fr)
运行结果:
6.斐波那契数
def fib(x): """assumes x an int >= 0 returns Fibonacci of x""" assert type(x) == int and x >= 0 if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2)
运行结果:
7.回文字符串:
def isPalindrome(s): def toChars(s): s = s.lower() ans = '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': ans = ans + c return ans def isPal(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPal(s[1:-1]) return isPal(toChars(s))
运行结果:
来自MIT的MOOC课件
相关文章推荐
- Python-goose:用于文章提取的Python库
- python-celery使用教程
- python的初级训练
- python-ConfigParser模块【读写配置文件】
- python字符串连接
- 【转】Python的异常处理机制
- 使用Python生成pdf文件
- [python]csv格式文件的使用
- 使用python进行机械设计计算
- Python学习之List
- 1.python环境搭建(python2.7.10+ PyCharm3.4.1/eclipse+selenium)
- 有关Python应用的21个小技巧
- python的基础概念
- python getopt使用
- python常见错误总结结
- python 元祖,列表,字典 初识
- Python Technical Notes
- python的unittest测试框架的扩展浅谈
- 比较perl+python
- 在IDEA上用python来连接集群上的hive