Example of reverse, sort, and sorted methods in Python

Source: Internet
Author: User
Tags in python

Reverse () method

Reverses the ordering of elements in a list, such as the following


>>> x = [1,5,2,3,4]
>>> X.reverse ()
>>> x
[4, 3, 2, 5, 1]
Reverse list Reverse Sort: stores the order of elements in the original list from left to right without sorting the parameters in the list. If you need to organize the parameters in a list, you need to sort the order in sort order by using another sort of list.

Sort () Sorting method

This function method makes a forward sort of the list content, and the sorted new list overwrites the original list (id invariant), which means that the sort sort method directly modifies the original list sort method.


>>> a = [5,7,6,3,4,1,2]
>>> A.sort ()
>>> A
[1, 2, 3, 4, 5, 6, 7]

Many Python beginners are more confused about the sort () method. Sometimes you'll need a sorted list, and you want to save the original unordered table, and they'll do the following:


>>> a = [5,7,6,3,4,1,2]
>>> B = A.sort ()
>>> Print B
None
This time the problem arises, and variable B gets a null value. What if you want to get a sorted list and keep the original list? List sorted () method can help you real

Sorted () method

That is, you can keep the original list, and you can get the sorted list sorted () operation method as follows:


>>> a = [5,7,6,3,4,1,2]
>>> B = Sorted (a)
>>> A
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]

The sorted () method can be used in a sequence of any data type and is always returned in a list form:


>>> sorted (' iplaypython.com ')
['. ', ' A ', ' C ', ' h ', ' I ', ' l ', ' m ', ' n ', ' o ', ' o ', ' P ', ' P ', ' t ', ' y ', ' y '
The difference between three people
Sort () is a method of a Mutable object (dictionary, list) with no arguments, no return value, and sort () that changes the Mutable object, so no return value is required. The sort () method is a method or property that is unique to a mutable object, and as immutable objects such as tuples and strings that do not have these methods, if the call returns an exception.


>>> a=[5,4,3,2,1]
>>> A.sort ()
>>>
>>> A
[1, 2, 3, 4, 5]

Sorted () is a built-in function of Python, not a unique method for mutable objects (lists, dictionaries), and the sorted () function requires a parameter (arguments can be lists, dictionaries, tuples, strings), and whatever arguments are passed, returns a value in the list as a container. If the dictionary will return the list of keys.


>>> mystring= "54321"
>>> mytuple= (5,4,3,2,1)
>>> mylist=[5,4,3,2,1]
>>> Sorted (mystring)
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
>>> Sorted (mytuple)
[1, 2, 3, 4, 5]
>>> Sorted (mylist)
[1, 2, 3, 4, 5]

Reverse () is used in the same way as sort, and reversed () is used in the same way as sorted ()


>>> mylist=[5,4,3,2,1]
>>> Mylist.reverse ()
>>> MyList
[1, 2, 3, 4, 5]
>>> mylist=[5,4,3,2,1]
>>> for I in Reversed (mylist):
... print I,
...
1 2 3 4 5

Through the slices of the sequence can also achieve a "reversal" effect


>>> mystring= "54321"
>>> mytuple= (5,4,3,2,1)
>>> mylist=[5,4,3,2,1]
>>> Mystring[::-1]
' 12345 '
>>> Mytuple[::-1]
(1, 2, 3, 4, 5)
>>> Mylist[::-1]
[1, 2, 3, 4, 5]

Summed up the common centralized sorting algorithm


Merge sort

Merge sort is also called merging sort, which is a typical application of partition method. The idea of divide-and-conquer is to decompose each problem into small problems, resolve each small problem, and then merge.
The specific merge sort is to decompose a group of unordered numbers into N/2 recursively, one element is already ordered. " These ordered child elements are then merged.
The merging process is to compare the smallest of the two subsequence to the two sorted subsequence, select the smallest of the two elements and move it from the subsequence
Remove the add to final result set until two subsequence merge complete.

The code is as follows:


#!/usr/bin/python
Import Sys

def merge (Nums, A, middle, last):
' The ' merge '
# slice boundaries, left and right open and is 0 for start
Lnums = nums[first:middle+1]
Rnums = nums[middle+1:last+1]
Lnums.append (Sys.maxint)
Rnums.append (Sys.maxint)
L = 0
R = 0
For I in Range (last+1):
If LNUMS[L] < Rnums[r]:
Nums[i] = Lnums[l]
L+=1
Else
Nums[i] = Rnums[r]
R+=1
def merge_sort (Nums, I, last):
"" "Merge sort
The Merge_sort function is passed the subscript, not the number of elements
'''
If < last:
Middle = (i + last)/2
Merge_sort (Nums, middle)
Merge_sort (Nums, middle+1, last)
Merge (Nums, middle,last)

if __name__ = = ' __main__ ':
Nums = [10,8,4,-1,2,6,7,3]
print ' nums is: ', nums
Merge_sort (nums, 0, 7)
print ' merge sort: ', nums

Stability, time complexity O (nlog N)

Insert Sort


#!/usr/bin/python 
Import sys 
  
def insert_sort (a): 
  & nbsp ' Insert sort
    has an ordered sequence of data that requires inserting a number in the sorted sequence of data,
    but the data sequence is still ordered after insertion. Just start with an element that is obviously orderly, then insert a
    element to the appropriate location, then insert a third element, and so on
    '  
     A_len = Len (a)  
    If A_len = 0 and A[j] > key: 
&NBSP;&NBSP;&NBSP;&NBSP;&NB sp;       a[j+1] = a[j] 
             j-=1 
        a[j+1] = key 
     return a 
  
If __name__ = = ' __main__ ': 
    nums = [10,8,4,-1,2, 6,7,3] 
    print ' nums is: ', nums 
    insert_sort (nums)  
&N bsp;   print ' Insert sort: ', nums

Stability, time complexity O (n^2)

Swap values for two elements python you can write this: a, B = B, A, which is actually because the left and right sides of the assignment symbol are tuples
(It should be emphasized that in Python, tuples are actually defined by commas "," rather than parentheses).
Select sort

Select sort (Selection sort) is a simple and intuitive sort algorithm. Its working principle is as follows. First, the smallest (large) element is found in the unordered sequence, which is stored in the
The starting position of the sort sequence, and then continue looking for the smallest (large) element from the remaining unordered elements, and then drop it at the end of the sorted sequence. And so on, until the
All elements are sorted and finished.


Import Sys
Def Select_sort (a):
"' Select sort
Each trip selects the smallest (or largest) element from the data element to be sorted,
The order is placed at the end of the sorted sequence until all the data elements that are ordered are finished.
Selecting a sort is an unstable sort method.
'''
A_len=len (a)
For I in Range (A_len): #在0-n-1 to select the element of the corresponding size in turn
Min_index = i# Record the subscript of the smallest element
For j in Range (I+1, A_len): #查找最小值
if (A[j]<a[min_index]):
Min_index=j
If Min_index!= I: #找到最小元素进行交换
A[i],a[min_index] = A[min_index],a[i]

if __name__ = = ' __main__ ':
A = [10,-3, 5, 7, 1, 3, 7]
print ' before sort: ', A
Select_sort (A)
print ' After sort: ', A
Instability, time complexity O (n^2)

Hill sort

Hill sort, also called the descending increment sort algorithm, Hill sort is a non stable sort algorithm. The method is also called narrowing the incremental order, due to DL. The shell was named after it was introduced in 1959.
First, take an integer d1 less than n as the first increment, dividing the entire record of the file into D1 groups. All records with a multiple distance of D1 are placed in the same group. First in each group of sorting;
Then, take the second increment d2<d1 repeat the grouping and sorting above until the incremental dt=1 (DT<DT-L<...<D2<D1) is taken, that is, all records are placed in the same group for direct insertion sort.


Import Sys
Def Shell_sort (a):
"" "Shell sort
'''
A_len=len (a)
gap=a_len/2# Increment
While gap>0:
For I in Range (A_len): #对同一个组进行选择排序
M=i
J=i+1
While J<a_len:
If A[J]&LT;A[M]:
M=j
J+=gap#j to Increase gap
If m!=i:
A[M],A[I]=A[I],A[M]
gap/=2

if __name__ = = ' __main__ ':
A = [10,-3, 5, 7, 1, 3, 7]
print ' before sort: ', A
Shell_sort (A)
print ' After sort: ', A
Unstable, time complexity average time O (nlogn) worst time O (n^s) 1<s<2
Heap sort (Heap sort)
Definition of "heap": In "heap" with starting index 0:
Node I of the right child node at position 2 * i + 24) node I of the parent node in position floor ((i-1)/2): Note floor means "rounding" operation
The characteristics of the heap:
The key value of each node must always be greater than (or less than) its parent node
"Max Heap":
The root node of the heap holds the node with the largest key value. That is, the key value of each node in the heap is always greater than its child nodes.
Move up, Move Down:
When a node's key value is greater than its parent node, then we are going to move up the action, that is, we moved the node to the location of its parent node,
and let its parent node go to its place, and then we continue to judge the node until the node is no longer larger than its parent node to stop moving up.
Now let's take a look at the move down operation. When we change the key value of a node, we need to move it down.
Method:
We first set up a maximum heap (time complexity O (n)), then each time we only need to swap the root node with the last location, and then exclude the last position, and then the exchange of the root node after the heap adjustment (Time complexity O (LGN)), that is, the root node to "Move Down" operation. The total time complexity of heap sorting is O (NLGN).
The code is as follows:


#!/usr/bin env python

# The array number starts at 0
def left (i):
return 2*i +1
def right (i):
Return 2*i+2

#保持最大堆性质 make a subtree with I root the largest heap
def max_heapify (A, I, heap_size):
If Heap_size <= 0:
Return
L = Left (i)
R = Right (i)
largest = i # Select the larger node in the child node
If L A[largest]:
largest = L
If R A[largest]:
Largest = R
If I!= largest: #说明当前节点不是最大的, Move Down
A[i], a[largest] = A[largest], A[i] #交换
Max_heapify (A, largest, heap_size) #继续追踪下移的点
#print A
# Build a heap
def bulid_max_heap (A):
Heap_size = Len (A)
If Heap_size >1:
node = HEAP_SIZE/2-1
While node >= 0:
Max_heapify (A, node, heap_size)
Node-=1

# heap sort subscript starting from 0
def heap_sort (A):
Bulid_max_heap (A)
Heap_size = Len (A)
i = heap_size-1
While i > 0:
A[0],a[i] = A[i], the maximum value in the a[0] # heap is stored in the appropriate location of the array and exchanged
Heap_size-=1 # Heap Size Descending 1
I-= 1 # subscript Descending 1 for maximum value in the heap
Max_heapify (A, 0, Heap_size)

if __name__ = = ' __main__ ':

A = [10,-3, 5, 7, 1, 3, 7]
print ' before sort: ', A
Heap_sort (A)
print ' After sort: ', A
Unstable, time complexity O (nlog N)
Quick Sort
The fast sort algorithm is also based on the partition mode, as is the merging sort algorithm. Sub-array A[P...R] The three steps of a fast sorting process are:
Decomposition: The array a[p...r] divided into a[p...q-1] and A[Q+1...R] two parts, where each element in a[p...q-1] is less than equal to a[q] and A[Q+1...R] Each element is greater than or equal to a[q];
Resolve: Sort by recursive invocation of fast ordering, a[p...q-1 of pairs] and A[Q+1...R];
Merging: Because two arrays are sorted in place, no extra action is required.
For the beginning of each iteration of the dividing partition, X=a[r], for any array subscript k, there are:
1) If p≤k≤i, then a[k]≤x.
2) If i+1≤k≤j-1, then a[k]>x.
3) If k=r, then a[k]=x.
The code is as follows:

#!/usr/bin/env python
# Quick Sort
'''''
Partitioning makes a division of the array of A[r] as the base, smaller than a[r] on the left,
Bigger than a[r] on the right.
There are two ways to quickly sort the partition process of partition,
One of the two pointer indices described above is a method of gradually scanning backwards,
Another method is to scan two pointers from the first to the middle.
'''
#p, R is the subscript of array A
def partition1 (A, P, R):
'''''
Method One, two pointers index one after the first step backward scan method
'''
x = A[r]
i = P-1
j = P
While J < r:
If A[J] < x:
I +=1
A[i], a[j] = A[j], a[i]
J + 1
A[I+1], a[r] = A[r], a[i+1]
Return i+1

def partition2 (A, P, R):
'''''
A method for scanning two pointers from the end to the middle
'''
i = P
j = R
x = A[p]
While i = x and I < j:
J-=1
A[i] = A[j]
While A[i]<=x and I < j:
I +=1
A[J] = A[i]
A[i] = X
return I

# Quick Sort
def quick_sort (A, P, R):
'''''
The worst time complexity for fast sorting is O (N2), and time complexity is O (NLGN)
'''
If P < r:
Q = Partition2 (A, p, R)
Quick_sort (A, p, q-1)
Quick_sort (A, q+1, R)

if __name__ = = ' __main__ ':

A = [5,-4,6,3,7,11,1,2]
print ' before sort: ', A
Quick_sort (A, 0, 7)
print ' After sort: ', A
Unstable, time complexity optimal O (Nlogn) worst time O (n^2)
Next, the sequence in Python:
Lists, tuples, and strings are sequences, but what are the sequences, and why are they so special? The two main features of the sequence are index operators and slicing operators. The index operator allows us to grab a specific item from the sequence. The slice operator allows us to get a slice of the sequence, which is part of a sequence, such as: a = [' AA ', ' BB ', ' cc '], print a[0] for indexing operations, and print a[0:2] for slicing operations.

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.