Python3 instances (eight)

Python merge sort

Merge sort (English: Merge sort, or mergesort), is to create a merge operation on an efficient sorting algorithm. The algorithm is very typical application uses a divide and conquer (Divide and Conquer) a.

Minute root treatment:

Segmentation: recursively divided equally in half the current sequence.

Integration: sequences while maintaining the order of the elements obtained in the previous step integrated together (merge).

Python3 instances (eight)

Examples

def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m

# 创建临时数组
L = [0] * (n1)
R = [0] * (n2)

# 拷贝数据到临时数组 arrays L[] 和 R[] 
for i in range(0 , n1): 
    L[i] = arr[l + i] 

for j in range(0 , n2): 
    R[j] = arr[m + 1 + j] 

# 归并临时数组到 arr[l..r] 
i = 0     # 初始化第一个子数组的索引
j = 0     # 初始化第二个子数组的索引
k = l     # 初始归并子数组的索引

while i < n1 and j < n2 : 
    if L[i] <= R[j]: 
        arr[k] = L[i] 
        i += 1
    else: 
        arr[k] = R[j] 
        j += 1
    k += 1

# 拷贝 L[] 的保留元素
while i < n1: 
    arr[k] = L[i] 
    i += 1
    k += 1

# 拷贝 R[] 的保留元素
while j < n2: 
    arr[k] = R[j] 
    j += 1
    k += 1

def mergeSort(arr,l,r):
if l < r:

    m = int((l+(r-1))/2)

    mergeSort(arr, l, m) 
    mergeSort(arr, m+1, r) 
    merge(arr, l, m, r) 

ARR = [12 is,. 11, 13 is,. 5,. 6,. 7]
n-= len (ARR)
Print ( "the given array")
for I in Range (n-):
Print ( "% D"% ARR [I]) ,

mergesort (ARR, 0, n-. 1)
Print ( "\ n \ after the n sorted array")
for I in Range (n):
Print ( "% D"% ARR [I]),
the above execution code output is :

Given array 121,113,567
array 567,111,213 sorted
Python heap sort

Heap sort (Heapsort) refers to a sorting algorithm such a data structure designed for use heap. Accumulation is a complete binary tree structure of approximation, while meeting the bulk properties: i.e. the key or index sub-node is always less than (or greater than) its parent node. Heap sort can be said is a use of the concept of heap to sort choose Sort.

Python3 instances (eight)

Examples

def heapify(arr, n, i):
largest = i
l = 2 i + 1 # left = 2i + 1
r = 2 i + 2 # right = 2i + 2

if l < n and arr[i] < arr[l]: 
    largest = l 

if r < n andarr[largest] < arr[r]: 
    largest = r 

if largest != i: 
    arr[i],arr[largest] = arr[largest],arr[i]  # 交换

    heapify(arr, n, largest) 

def HeapSort (district):
n = len (arr)

# Build a maxheap. 
for i in range(n, -1, -1): 
    heapify(arr, n, i) 

# 一个个交换元素
for i in range(n-1, 0, -1): 
    arr[i], arr[0] = arr[0], arr[i]   # 交换
    heapify(arr, i, 0) 

ARR = [12 is,. 11, 13 is,. 5,. 6,. 7]
heapSort (ARR)
n-= len (ARR)
( "sorted") Print
for I in Range (n-):
Print ( "% D"% ARR [I ]),
the above output is executing code:

Sorted
. 5
. 6
. 7
. 11
12 is
13 is
the Python counting sequencing

Core sorted count value that the input data is converted to the key stored in an array of additional space open. A linear sort time complexity, the data input count ordering requirements must be integers determined range.

Examples

def countSort(arr):

output = [0 for i in range(256)] 

count = [0 for i inrange(256)] 

ans = ["" for _ in arr] 

for i in arr: 
    count[ord(i)] += 1

for iin range(256): 
    count[i] += count[i-1] 

for i in range(len(arr)): 
    output[count[ord(arr[i])]-1] = arr[i] 
    count[ord(arr[i])] -= 1

for i inrange(len(arr)): 
    ans[i] = output[i] 
return ans  

= ARR "wwwrunoobcom"
ANS = countSort (ARR)
Print (. "character array sort% s"% ( "" join (ans)))
to perform the above code is output is:

Character array sort bcmnoooruwww
Python Shell sort

Hill sort, also known as incremental descending sorting algorithms, insertion sort is a more efficient improved version. But Hill sorting non-stationary sorting algorithm.

Hill is the basic idea of ​​the sort: the entire sequence of records to be sorted first divided into several sub-sequences respectively direct insertion sort, until the entire record in the sequence of "basic order", the re-recording of all direct insertion sort order.

Python3 instances (eight)

Examples

def shellSort(arr):

n = len(arr)
gap = int(n/2)

while gap > 0: 

    for i inrange(gap,n): 

        temp = arr[i] 
        j = i 
        while  j >= gap and arr[j-gap] >temp: 
            arr[j] = arr[j-gap] 
            j -= gap 
        arr[j] = temp 
    gap = int(gap/2)

arr = [ 12, 34, 54, 2, 3]

n = len(arr)
print ("排序前:")
for i inrange(n):
print(arr[i]),

shellSort(arr)

print ( "\ n After sorting:")
for I in Range (n):
Print (ARR [I]),
the implementation of the above code is output is:

Before sorting:
12 is
34 is
54 is
2
. 3
sorted:
2
. 3
12 is
34 is
54 is
the Python topological sorting

For a directed acyclic graph (Directed Acyclic Graph referred to as the DAG) G be topologically sorted, all the vertices of G is arranged in a linear sequence, such that any pair of vertices FIG u and v, if the edge (u, v) ∈ E (G), the linear sequence u appears before v.

Typically, such a sequence is called a linear sequence satisfy topological order (Topological Order), acronym topology sequence. Briefly, to give a total order on the set of a partial order on a set, this operation is called Topological Sort.

在图论中,由一个有向无环图的顶点组成的序列,当且仅当满足下列条件时,称为该图的一个拓扑排序(英语:Topological sorting):

每个顶点出现且只出现一次;

若A在序列中排在B的前面,则在图中不存在从B到A的路径。

Python3 instances (eight)

实例

from collections import defaultdict

class Graph:
def init(self,vertices):
self.graph = defaultdict(list)
self.V = vertices

def addEdge(self,u,v): 
    self.graph[u].append(v) 

def topologicalSortUtil(self,v,visited,stack): 

    visited[v] = True

    for i in self.graph[v]: 
        if visited[i] == False: 
            self.topologicalSortUtil(i,visited,stack) 

    stack.×××ert(0,v) 

deftopologicalSort(self): 
    visited = [False]*self.V 
    stack =[] 

    for i inrange(self.V): 
        if visited[i] == False: 
            self.topologicalSortUtil(i,visited,stack) 

    print (stack) 

g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);

print ("拓扑排序结果:")
g.topologicalSort()
执行以上代码输出结果为:

拓扑排序结果:
[5, 4, 2, 3, 1, 0]
最后免费赠送一个实例:

Python 计算笛卡尔积

计算多个集合的笛卡尔积,有规律可循,算法和代码也不难,但是很多语言都没有提供直接计算笛卡尔积的方法,需要自己写大段大段的代码计算笛卡尔积,python 提供了一种最简单的计算笛卡称积的方法(只需要一行代码),详见下面的代码:
#!/usr/bin/python3

-- coding: utf-8 --

@file : Cartesian.py

@author : shlian

@date : 2018/5/29

@version: 1.0

@desc : 用python实现求笛卡尔积

import itertools

class cartesian(object):
def init(self):
self._data_list=[]

def add_data(self,data=[]): #添加生成笛卡尔积的数据列表
    self._data_list.append(data)

def build(self): #计算笛卡尔积
    for item in itertools.product(*self._data_list):
        print(item)

if name=="main":
car=cartesian()
car.add_data([1,2,3,4])
car.add_data([5,6,7,8])
car.add_data([9,10,11,12])
car.build()
计算的结果如下:
(1, 5, 9)
(1, 5, 10)
(1, 5, 11)
(1, 5, 12)
(1, 6, 9)
(1, 6, 10)
(1, 6, 11)
(1, 6, 12)
(1, 7, 9)
(1, 7, 10)
(1, 7, 11)
(1, 7, 12)
(1, 8, 9)
(1, 8, 10)
(1, 8, 11)
(1, 8, 12)
(2, 5, 9)
(2, 5, 10)
(2, 5, 11)
(2, 5, 12)
(2, 6, 9)
(2, 6, 10)
(2, 6, 11)
(2, 6, 12)
(2, 7, 9)
(2, 7, 10)
(2, 7, 11)
(2, 7, 12)
(2, 8, 9)
(2, 8, 10)
(2, 8, 11)
(2, 8, 12)
(3, 5, 9)
(3, 5, 10)
(3, 5, 11)
(3, 5, 12)
(3, 6, 9)
(3, 6, 10)
(3, 6, 11)
(3, 6, 12)
(3, 7, 9)
(3, 7, 10)
(3, 7, 11)
(3, 7, 12)
(3, 8, 9)
(3, 8, 10)
(3, 8, 11)
(3, 8, 12)
(4, 5, 9)
(4, 5, 10)
(4, 5, 11)
(4, 5, 12)
(4, 6, 9)
(4, 6, 10)
(4, 6, 11)
(4, 6, 12)
(4, 7, 9)
(4, 7, 10)
(4, 7, 11)
(4, 7, 12)
(4, 8, 9)
(4, 8, 10)
(4, 8, 11)
(4, 8, 12)

好了,本文就给大伙分享到这里,文末分享一波福利

Here Insert Picture Description

Python3 instances (eight)

获取方式:加python群 839383765 即可获取!

Guess you like

Origin blog.51cto.com/14186420/2409494