Python實現:函數的遞迴(樣本)

來源:互聯網
上載者:User

標籤:求和   排序   end   print   相等   type   highlight   start   quick   

#1,用遞迴實現計算函數的階乘
def myfac(n): #用迴圈實現 s= 1 for i in range(1,n+1): s*=i print(s)myfac(5)def myfac(n): #用迴圈實現 if n==1: return 1 return n*myfac(n-1)print(myfac(5))

 

#2,用遞迴實現求和: def mysum(n):    #返回1+2+3+4+5+n的和print(mysum(100))#5050def  mysum(n):    if n==1:        return 1    return n+mysum(n-1)print(mysum(100))

 

 

3.已知有列表
L=[[3,5,8],10,[[13,14,],15,18],20]
寫一個函數print_list(lst)列印出所有的數字
寫一個函數 sum_list(lst)返回列表中所有數字
的和
註:
type(x)函數可以返回一個對象的類型
>>>type(20) is int #True
type([3,5,8]) is list #True

def print_list(lst):    # l=[]    for x in lst:        if type(x) is int:            # print_list(x)            print(x)        else:            print_list(x)            # print(x)def sum_list(lst):    sum=0    for x in lst:        if type(x) is list:            sum+=sum_list(x)        else:            sum+=x    return sumL=[[3,5,8],10,[[13,14,],15,18],20]print_list(L)print(sum_list(L))

 

4,用遞迴的方法實現快速排序

def QuickSort(myList,start,end):    if start < end:        i,j = start,end        #設定基準數        base = myList[i]        while i < j:            #如果列表後邊的數,比基準數大或相等,則前移一位直到有比基準數小的數出現            while (i < j) and (myList[j] >= base):                j = j - 1            #如找到,則把第j個元素賦值給第個元素i,此時表中i,j個元素相等            myList[i] = myList[j]            #同樣的方式比較前半區            while (i < j) and (myList[i] <= base):                i = i + 1            myList[j] = myList[i]        #做完第一輪比較之後,列表被分成了兩個半區,並且i=j,需要將這個數設定回base        myList[i] = base        #遞迴前後半區        QuickSort(myList, start, i - 1)        QuickSort(myList, j + 1, end)    return myListmyList = [49,38,65,97,76,13,27,49]print("Quick Sort: ")QuickSort(myList,0,len(myList)-1)print(myList)

 

 

Python實現:函數的遞迴(樣本)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.