您的位置:首页 > 编程语言 > Python开发

迭代和递归(Python)--乘方、最大公约数、汉诺塔、斐波那契、回文字符串

2015-07-23 15:24 771 查看
1.迭代

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课件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: