1. 程式人生 > >python-23-遞迴:這幫小兔崽子

python-23-遞迴:這幫小兔崽子

1.兔子的非遞迴方式:

def fei(n):
    n1=1
    n2=1
    n3=1
    if n<1:
        return -1
    while(n-2)!=0:
        n3=n1+n2
        n1=n2
        n2=n3
        n-=1
    return n3
result=fei(40)

print('20對兔子能生%d對兔崽子',result)

遞迴方式:

def fab(n):
if n<1:
print('輸入有誤!')
return -1
if n==1 or n==2:
return 1
else:
return fab(n-1)+fab(n-2)
result=fab(45)

print('總共有%d對小兔崽子誕生'%result)

2.

用遞迴的方式解決漢諾塔問題:

    def hannoi(n,x,y,z):  
        if n == 1:  
            print(x,'-->',z)  
        else:  
            hannoi(n-1,x,z,y)#將前n-1個盤子移動到y上  
            print(x,'-->',z)#將最底下的盤子移動到z上  
            hannoi(n-1,y,x,z)#將y上的n-1個盤子移動到z上  

    n = int(input('請輸入漢諾塔的層數:'
))

hannoi(n,'X','Y','Z')

典型課後題  使用遞迴編寫一個十進位制轉換為二進位制的函式(要求採用“取2取餘”的方式,結果與呼叫bin()一樣返回字串形式)。

    def Bin(n):  
        temp = ''  
        if n:  
            temp = Bin(n//2)  
            temp += str(n%2)  
            return temp  
        else:  
            return temp          

    num = int(input('請輸入一個十進位制數:'
)) print(num,'-->',Bin(num))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

寫一個函式get_digits(n),將引數n分解出每個位的數字並按順序存放到列表中。舉例:get_digits(12345) ==> 
[1, 2, 3, 4, 5]

解題思路:利用除以10取餘數的方式,每次呼叫get_digits(n//10),並將餘數存放到列表中即可。要注意的是結束條件 
設定正確。

    def get_digits(n):  
        result = ''  
        if n:  
            result = get_digits(n//10)  
            result += str(n%10)  
        return list(result)  

    num = int(input('請輸入一個數:'))  
    print(get_digits(num))  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

還記得求迴文字串那道題嗎?現在讓你使用遞迴的方式來求解,親還能傲嬌的說我可以嗎?

解題思路:有好多種方法,不過綜合效率來說,小甲魚的實現方式比較樸素,利用遞迴每次索引前後兩個字元進行對 
比,當start > end的時候,也正是首尾下標“碰面”的時候,即作為結束遞迴的條件。

def huiWen(temp,start,end):
    if start>end:
        return 1
    else:
        if temp[start]==temp[end]:
            return huiWen(temp,start+1,end-1)
        else:
            0
temp=input('請輸入一個字串:')
length=len(temp)
end=length-1
if huiWen(temp,0,end):
    print('%s是一個迴文字串'%temp)
else:
    print('%s不是一個迴文字串'%temp)
    def Age(n):
    if n==1:
        return 10
    if n>1:
        age=10
        age=Age(n-1)+2
        return age
n=int(input('請輸入是第幾個人:'))
print('第%s個人是%d歲'%(n,Age(n)))