學習python之路---python小演算法總結(四)

來源:互聯網
上載者:User

題目16:合并排序Python實現

外部排序——合并排序原理

合并排序法基本是將兩筆已排序的資料合併並進行排序,如果所讀入的資料尚未排序,可以先利用其它的排序方式來處理這兩筆資料,然後再將排序好的這兩筆資料合併。

importrandom

importcopy

number1 =random.sample(range(100), 10)

number2 =random.sample(range(100), 10)

number1.sort()

number2.sort()

defrecursive_sort(listA, listB):

    """

        遞迴實現

    """

    iflen(listA) == 0:

        return listB

    elif len(listB) == 0:

        return listA

    elif listA[0] < listB[0]:

        return [listA[0]] +recursive_sort(listA[1:], listB)

    else:

        return [listB[0]] +recursive_sort(listB[1:], listA)

defsort(listA, listB):

    """

        非遞迴實現

    """

    len_A = len(listA)

    len_B = len(listB)

    if len_A == 0:

        return listB

    elif len_B == 0:

        return listA

    else:

        i = 0

        j = 0

        listC = []

        while i < len_A and j < len_B:

            if listA[i] <= listB[j]:

                listC.append(listA[i])

                i += 1

            else:

                listC.append(listB[j])

                j += 1

        while i < len_A:

            listC.append(listA[i])

            i += 1

        while j < len_B:

            listC.append(listB[j])

            j += 1

    return listC

printnumber1

printnumber2

listC =recursive_sort(number1, number2)

printlistC

listC =sort(number1, number2)

運行結果如下:

[9, 15, 20, 27, 32, 33, 56, 62,78, 84]

[29, 35, 46, 50, 66, 69, 84,87, 89, 90]

[9, 15, 20, 27, 29, 32, 33, 35, 46, 50, 56,62, 66, 69, 78, 84, 84, 87, 89, 90]


題目17:遍曆字串

theString = 'Ix lixkxex xpxytxhxonx !'
defPrintEngine(c):
ifc != 'x':
printc,
map(PrintEngine,theString)

輸出結果:I   l i k e   p y t h o n  !



題目18: 除法小技巧

Python中將兩個整數相除,預設結果是整數。使用如下語句,可以得到相除的結果為小數

from __future__ import division
print7/3
輸出結果:

2.3333333333

 

 

 

題目19:列印字串格式

print '|','*'.ljust(10),'|'

print '|','*'.ljust(10,'-'),'|'

print '|','*'.rjust(10,'-'),'|'

print '|','*'.center(10,'-'),'|'

for a in range(1, 6):

print 'a ='.ljust(5), repr(a).ljust(10), 'b = '.ljust(5), repr(a * 2)

| * |
|*--------- |
|---------* |
|----*----- |
a= 1 b = 2
a= 2 b = 4
a= 3 b = 6
a= 4 b = 8
a= 5 b = 10


題目20:初始化多維陣列

Python中初始化一個5X3每項為0的數組,較好的方法是

multilist = [[0 for col in range(5)] forrow in range(3)]

multilist[0][0]='love china'

 print multilist

[['love china', 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.