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

来源:互联网 发布:java泛型有什么用 编辑:程序博客网 时间:2024/05/21 17:25

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课件

0 0
原创粉丝点击