1. 程式人生 > >迭代和遞迴(Python)--乘方、最大公約數、漢諾塔、斐波那契、迴文字串

迭代和遞迴(Python)--乘方、最大公約數、漢諾塔、斐波那契、迴文字串

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