Python full stack Development 5. Several Common sorting algorithms and the data structure provided by the collections module, pythoncollections

Source: Internet
Author: User

Python full stack Development 5. Several Common sorting algorithms and the data structure provided by the collections module, pythoncollections

During the interview, I often encounter some questions about the sorting algorithm. Here, I simply listed several of the most common sorting algorithms for you to learn. Maybe the interview will be useful in the future, the second half of this article introduces the collections module, because this module is not familiar with the basic data structure (list, tuple, dict) provided by python, but if you know them, it is also very convenient and efficient to use.

Sort Algorithm 1. BubbleSort)

Steps:

  • Compare adjacent elements. If the first element is larger than the second element, exchange the two adjacent elements.
  • After repeating the loop, the maximum number is "floating" to the final position of the list.
  • Repeat the remaining number and sort all the paths.

The Code is as follows:

Def swap (a, B ): # a method that cleverly exchanges the positions of two numbers without the third variable. a = B-a B = B-a # B = B-(B-) = 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 ): # I reduction in each cycle is due to the fact that the last number has sorted the order if l [j]> l [j + 1]: l [j], l [j + 1] = l [j + 1], l [j] # exchange two numbers, here, the exchange is the unique return lprint (BubbleSort ([555, 2, 3, 2, 3, 1, 19, 3.5,]) in python) # [1, 2, 2, 2, 3, 3, 3.5, 19, 24, 27,555]
Ii. Select and sort SelectionSort

Steps:

  • Find the smallest (large) element in the unordered sequence and store it to the starting position of the sorting sequence.
  • Then, find the smallest (large) element from the remaining unordered elements and put it at the beginning of the sorting sequence.
  • Loop down, sorting all the numbers in the direct path is completed

The Code is as follows:

Def SelectionSort (l): for I in range (len (l): min = I # subscript for j in range (I + 1, len (l )): if l [j] <l [min]: min = j # Write down the subscript of the smallest element l [I], l [min] = l [min], l [I] # Put the minimum element in the start position of the List return lprint (SelectionSort ([555, 2, 3, 1, 19, 3.5, 27,24]) # [1, 2, 2, 2, 3, 3, 3.5, 19, 24, 27,555]
Iii. Insert sorting InsertionSort

Steps:

  • Starting from the first element, we can consider it to have been sorted, take out the next element, and scan the sorted element sequence from the back to the front.
  • If the element (sorted) is greater than the new element, move the element to the next position until it finds the position where the sorted element is smaller than or equal to the new element.
  • After the new element is inserted to this position, all the paths are sorted in this repeating order.

The Code is as follows:

Def InsertionSort (l): for I in range (1, len (l): if l [I] <l [I-1]: temp = l [I] # The number of inserts should be assigned to the variable temp for j in range (I-1,-1,-1 ): # From the sorted sequence forward loop if l [j]> temp: l [j + 1] = l [j] index = j # Write down the position else to be inserted: break l [index] = temp return lprint (InsertionSort ([555, 2, 3, 3, 1, 19, 3.5, 27,24]) # [1, 2, 2, 3, 3, 3.5, 19, 24, 27,555]
Iv. Quick sorting

Steps:

  • Pick an element from the sequence as the reference number (here I select the first number)
  • Place the number greater than the baseline number to the left, and the number smaller than or equal to the baseline number to the right.
  • Perform the previous step recursively on the left and right intervals until each interval has only one number.

The Code is as follows:

# Here I use recursion and list push (the list push type can be skipped temporarily, but I will talk about it later) def QuickSort (l): if len (l) <= 1: return l return QuickSort ([lt for lt in l [1:] if lt <l [0]) + l [] + QuickSort ([ge for ge in l [1:] if ge> = l [0]) print (QuickSort ([555, 2, 3, 2, 3, 1, 19, 3.5, 3.5]) # [1, 2, 2, 3, 3, 27,555, 19, 24,]

For the moment, there are so many sorting algorithms, some of which are not written, and some can also be implemented using several different methods. If there is enough time in the future, we will improve the sorting algorithm, the following describes the collctions module.

Collections Module 1. deque

Deque is a dual-end queue. Remember the previous list. In general, it is added and deleted from the end, while deque allows adding or deleting elements from any end. deque is similar to list in usage, the following code mainly describes some specific usage,

# Native list can also add and retrieve elements from the header. the time complexity of the two usage methods of list objects is O (n ), # That is to say, the time consumed increases linearly as the number of elements increases, while the complexity of using a deque object is O (1) from collections import dequed = deque ('afd ') print (type (d) # <class 'collections. deque '> d. appendleft ([, 3]) # insert columns from the Left to print (d) # deque ([1, 2, 3], 'A', 'D ', 'F']) d. extendleft ('gssg') # Extend an iteratable object from the left side print (d) # deque (['G', 's', 's', 'G ', [1, 2, 3], 'A', 'D', 'F']) print (d. popleft () # remove elements from the left end from the source pair (g) # deque (['s', 's', 'G', [1, 2, 3], 'A', 'D', 'F']) d. rotate (1) #1 represents a step of loop movement, equivalent to d. appendleft (d. pop () print (d) # deque (['F', 's', 's', 'G', [1, 2, 3], 'A ', 'D']) print (d [4]) # indexes supported, [1, 2, 3] for I in d: print (I) # for loops supported # in addition, index (), append (), extend (), reverse (), remove (), pop (), insert () and other methods are the same as the list, so we will not talk about them anymore.
Ii. namedtuple

Namedtuple () is used to create a customtupleObject and specifiestupleNumber of elements, which can be referenced by attributes rather than Indexestuple.

From collections import namedtuple # if we want to use tuples to represent a vertex (x, y), # in this way, we can use namedtuple, # It has tuple immutability and can reference Point = namedtuple ('point', ['x', 'y']) based on attributes. # Use the namedtuple function, create a custom tuple object Pointp1 = Point (11, y = 2) # create an instance p1p2 = Point (2, 3) print (p1.x) #11 obtain the value print (p2 [1]) based on the attribute #3 also supports index p3 = Point (* (55,22) # Use * to convert print (p3.x) to input tuples) #55p4 = Point (** {'X': 1, 'y': 1}) # Use ** to convert print (p4.x) into a dictionary #1
Iii. defaultdict

UsedictIf the referenced Key does not existKeyError, and there is no has_key method in py3. You need to use in before each use.. If you want to return a default value when the key does not exist, you can usedefaultdict。

# Pass in a default factory method. When a non-existent key is requested, # Calls the factory method and uses the result as the default value of the key. Dd = defaultdict (lambda: 'na') # Call the lammbda function dd ['X'] = 2 print (dd ['y']) when the key does not exist # The key does not exist, return NAprint (dd ['X']) # exist, value: 2 print (dd) # defaultdict (<function <lambda> .., {'X': 2, 'y': 'na'}) # defaultdict has another magical usage. For Statistics, see the following code s = [('yellow ', 1), ('Blue ', 2), ('yellow', 3), ('Blue', 4), ('red', 1)] d = defaultdict (list) for k, v in s: d [k]. append (v) # returns a list when the key does not exist, and then adds the corresponding element print (d) # defaultdict (<class 'LIST'>, {'yellow ': [1, 3], 'red': [1], 'blue': [2, 4]})
4. OrderedDict

When using dict in the past, because dict is unordered, it is always impossible to do loop iteration. If we want to keep the Key order, we can use OrderedDict, note that the Key sequence refers to the Key insertion sequence, rather than the Key sequence.

From collections import ordereddictodd = OrderedDict () od ['X'] = 1od ['y'] = 2od ['a'] = 3 print (od) # OrderedDict ([('x', 1), ('y', 2), ('A', 3)]) for I in od: print (I) # print the order x-> y-> a. You can try it several times to see if the result is the same print (od. popitem () # ('A', 3), LIFO (first-in-first-out)
V. Counter

CounterYesdictA subclass of is a simple counter. Let's take a look at its usage.

From collections import Counterc1 = Counter ('ddkhbb') # Pass in an iteratable object print (c1) # Counter ({'D': 2, 'B': 2, 'H': 1, 'K': 1}) print (c1 ['D']) #2 # counter update, add c1.update ('kkk ') print (c1) # Counter ({'K': 4, 'D': 2, 'B': 2, 'H': 1}) # update the Counter to reduce c1.subtract ('kkkkkkkkkk ') print (c1) # Counter ({'D': 2, 'B': 2, 'H': 1, 'K':-4}) # elements returns an iterator, the number of times that an element has been repeated. # Elements smaller than 1 are not included. Print (list (c1.elements () # ['h', 'D', 'D', 'B ', 'B'] print (c1.most _ common (2) # extract up to two elements ('B', 2), ('D', 2)]

  

  

  

  

 

Related Article

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.