本文主要是介绍迭代和递归(Python)--乘方、最大公约数、汉诺塔、斐波那契、回文字符串,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.迭代
def iterPower(base,exp):result=1.0while exp>0:result*=baseexp-=1return result
运行结果:
2.递归的乘法运算:
def recurMul(a,b):if b==1:return aelse:return a+recurMul(a,b-1)
运行结果:
3.递归乘方:
def recurPowerNew(base,exp):if exp==0:return 1elif 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=1while r!=0:r=a%ba=bb=r return a
运行结果:
递归:
def gcdRecur(a,b):if b==0:return aelse: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 >= 0returns Fibonacci of x"""assert type(x) == int and x >= 0if x == 0 or x == 1:return 1else: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 + creturn ansdef isPal(s):if len(s) <= 1:return Trueelse:return s[0] == s[-1] and isPal(s[1:-1])return isPal(toChars(s))
运行结果:
来自MIT的MOOC课件
这篇关于迭代和递归(Python)--乘方、最大公约数、汉诺塔、斐波那契、回文字符串的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!