Python full stack development 5, several common sorting algorithms and the data structure provided by the collections module

Source: Internet
Author: User

In the interview, often encounter some of the problem of sorting algorithm, here, I simply listed a few of the most common sorting algorithms for everyone to learn, perhaps the next day interview exactly use, the second half of the article introduces the collections module, because this module relative to the basic data structure provided by Python (list,tuple,dict) are not familiar to people, but if you know them, it is very convenient and efficient to use them.

Sort algorithm One, bubble sort (bubblesort)

Steps:

    • Compare adjacent elements, and if the first one is larger than the second one, swap them both.
    • Once the loop is over, the largest number floats to the final position of the list.
    • Loop the rest of the numbers again, straight to the finish of all sorts

The code is as follows:

Def swap (A, b):          #一种巧妙交换两个数的位置而不用第三个变量的方法    a=b-a    b=b-a                # b=b-(b-a) = a    a=b+a                # a=a+ (b-a) = b
   
    return a,bdef Bubblesort (L):    # bubble sort for    i in range (1,len (L)): for        J in Range (0,len (l)-i): # each cycle minus I is because the last number is already ordered            if L[J]>L[J+1]:                l[j],l[j+1]=l[j+1],l[j] # Exchange two numbers, the exchange here is a unique way of exchanging in Python    return Lprint (Bubblesort ([555,2,3,2,3,1,19,3.5,27,24]) # [1, 2, 2, 3, 3, 3.5, 19, 24, 27, 555]
   
Second, choose the sort Selectionsort

Steps:

    • Finds the smallest (large) element in an unordered sequence, and holds it to the starting position of the sort sequence.
    • Then continue looking for the smallest (large) element from the remaining unsorted elements, and then place the start of the sort sequence.
    • Loop down, straight all the numbers sorted out

The code is as follows:

def selectionsort (L): for    I in range (Len (l)):        min = i                                 #存放最小元素的下标 for J in        Range (I+1,len (l)):            if l[ J]<l[min]:                min=j                          #记下最小元素的下标        l[i],l[min] = l[min],l[i]              #将最小元素放到列表起始位置    return Lprint (Select Ionsort ([555,2,3,2,3,1,19,3.5,27,24]) #[1, 2, 2, 3, 3, 3.5, 19, 24, 27, 555]
Iii. inserting sort Insertionsort

Steps:

    • From the beginning of the first element can be thought to have been sorted, take out the next element, in the ordered sequence of elements from the back forward scanning
    • If the element (sorted) is greater than the new element, move the element to the next position until the sorted element is found to be less than or equal to the position of the new element
    • After inserting the new element into the position, the loop is repeated so that all the rows are ordered

The code is as follows:

def insertionsort (L): for    I in range (1,len (l)):        if l[i]<l[i-1]:            temp=l[i]                               # Assign a value to the variable temp            For j in Range (i-1,-1,-1):              # Loop forward from the queued sequence                if l[j]>temp:                    l[j+1] = l[j]                    index=j                         # Note the position                that should be inserted else:                    break            l[index]=temp    return Lprint (Insertionsort ([555,2,3,2,3,1,19,3.5,27,24])   # [1, 2, 2, 3, 3, 3.5, 19, 24, 27, 555]
Iv. Quick Sort QuickSort

Steps:

    • Pick an element from the series as the base number (I chose the first number here)
    • Place the number larger than the base number on the left, less than or equal to it, and put it on the right.
    • Then the left and right intervals are recursively executed in the previous step until each interval has only one number

The code is as follows:

#这里我用了递归和列表推到式 (do not understand the list push-to-type can be skipped temporarily, said later) def QuickSort (l):    If Len (l) <=1:        return L    return QuickSort ([LT for Lt in L[1:] if lt<l[0] ") + l[0:1] + QuickSort ([ge for GE in l[1:] if ge>=l[0]]) print (QuickSort ([555,2,3,2,3,1,19,3.5 , 27,24])   # [1, 2, 2, 3, 3, 3.5, 19, 24, 27, 555]

Sorting algorithm for the time to write so much, there are some sort algorithm is not written, and some sorting algorithm can be implemented in several different ways, if the following times are sufficient, then to improve, the following talk about Collctions module

Collections Module One, deque

Deque is a double-ended queue, remember the previous list, in general, is to add the deletion from the tail, and deque allow to add or remove elements from either end, deque usage and list very much like, the following code mainly to look at some of the specific usage,

 #原生的list也可以从头部添加和取出元素, the time complexity of these two usages of the list object is O (n), #也就是说随着元素数量的增加耗时呈线性上升, The Deque object is the complexity of O (1) from collections import Dequed=deque (' ADF ') print (type (d)) # <class ' Collectio Ns.deque ' >d.appendleft ([3]) # Insert Column alias print (d) # deque from the Left ([[1, 2,], ' a ', ' d ', ' F ']) d.extendleft (' GSSG ') # extends an iterative object from the left side print (d) # deque ([' G ', ' s ', ' s ', ' G ', [1, 2, 3], ' A ', ' d ', ' F ']) print (D.popleft ()) # left side Delete element Gprint (d) # deque ([' s ', ' s ', ' G ', [1, 2, 3], ' A ', ' d ', ' F ']) D.rotate (1) # 1 represents the loop move one step, equivalent to D.appendleft (D.pop ()) Print  (d) # deque ([' F ', ' s ', ' s ', ' G ', [1, 2, 3], ' A ', ' d ']) print (d[4]) # Support index, [1, 2, 3]for i in D:print (i) # support for loop # In addition, index (), append (), extend (), reverse (), remove () , Pop (), insert (), and so on, don't say 
Second, namedtuple

Namedtuple () is used to create a custom tuple object, and it specifies the tuple number of elements and an element that can be referenced by a property rather than an index tuple .

From collections Import namedtuple# if we want to use a tuple to represent a point (x, y), # This is not very clear to express the meaning, this time can be used namedtuple,# it has a tuple invariance, You can also refer to point=namedtuple (' point ', [' X ', ' Y ']) by property to  create a custom tuple object Pointp1=point (11,y=2) with the Namedtuple function                     # Create an instance of P1p2=point (2,3) print (p1.x)                          # One  per property to get the value print (p2[1])                         # 3   also supports index p3=point (* (55,22))                   # When passing in a tuple, convert print (p3.x)                          # 55p4=point (**{' x ': 1, ' Y ': 1})            # Convert print (p4.x) # 1 into a dictionary                          
Third, defaultdict

dictwhen used, if the referenced key does not exist, it will be thrown KeyError,而且py3中没有has_key的方法,每次使用前需要使用in判断 . If you want the key to not exist, return a default value, you can use thedefaultdict。

#传入一个默认的工厂方法, #便会调用这个工厂方法使用其结果来作为这个key的默认值 when a nonexistent key is requested. Dd=defaultdict (lambda: ' NA ')         # When key does not exist call Lammbda function dd[' x ']=2print (dd[' y ')                       # key does not exist, return Naprint (dd[' x '])                       # exists with a value of 2print (DD)                            # defaultdict (<function <lambda> at:, {' X ' 2, ' y ': ' NA '}) #defaultdict还有一种神奇的用法, used as a statistic, Look at the code below s = [(' Yellow ', 1), (' Blue ', 2), (' Yellow ', 3), (' Blue ', 4), (' Red ', 1)]d = defaultdict (list) for K, V in S:    D[k] . Append (v)  # Key does not exist when you return a list and then add the corresponding element with append print (d)            # defaultdict (<class ' list '), {' Yellow ': [1, 3], ' Red ': [1], ' Blue ': [2, 4]}
Iv. ordereddict

Before using Dict, because dict is unordered always can not do loop iteration, etc., if we want to maintain the order of key can use ordereddict, note that the order of key here refers to the order of key insertion, rather than the key itself sort.

From collections Import ordereddictod=ordereddict () od[' x ']=1od[' y ']=2od[' a ']=3print (OD)             # ordereddict ([' X ', 1) , (' Y ', 2), (' A ', 3)]) for i in OD: Print    (i)          # Printing order x->y->a, readers can go down and try to see if the results are the same print (Od.popitem ())   # Will (' A ', 3) Popup, LIFO (LIFO)
Wu, Counter

Counteris a dict sub-class, is a simple counter, the following look at his usage

From collections Import counterc1=counter (' Ddkhbb ')         # incoming an iterative object print (C1)                    # Counter ({' d ': 2, ' B ': 2, ' h ': 1, ' K ': 1}) Print (c1[' d ')               # c counter update, increase c1.update (' KKK ') print (C1)                    # Counter ({' K ': 4, ' d ': 2, ' B ': 2, ' H ': 1}) # counter The update that reduces c1.subtract (' kkkkkkkk ') print (C1)                    # Counter ({' d ': 2, ' B ': 2, ' h ': 1, ' K ':-4}) # elements returns an iterator to how many times the element was repeated in that iteration How many of the elements are included in the device. # Elements with a number less than 1 are not included. The number of k less than 1 is excluded from print (List (c1.elements ()))   # [' H ', ' d ', ' d ', ' B ', ' B ']print (C1.most_common (2))     #取出出现次数最多2个元素 [(' B ', 2), (' d ', 2)]

  

  

  

  

Python full stack development 5, several common sorting algorithms and the data structure provided by the collections module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.