Python algorithm Tutorial chapter II Knowledge Points: Timing module, dictionary and hash table, graph and tree implementation, member query, insert Object

Source: Internet
Author: User

This document lists: one, time module; second, dictionary and hash hash table; Third, the realization of the graph and the tree; Iv. member query; Insert Object
</br>
One, timing module (Timeit, CProfile)

import timeittimeit.timeit(‘x = 1 + 2‘)

Since learning the algorithm, it is important to calculate the time spent on the program, but it should be noted that: the Timeit () Timing function runs the relevant code snippet multiple times and averages it to improve the accuracy of the timing, so we need to prevent the execution of the code after the previous execution operation has affected it. For a chestnut: if we perform a sort algorithm, only the first execution of the code is timed at random, and the remaining thousands of runs run on the premise of the sequence table, which results in a low final timing result. Therefore, you can try using the Cprofile module.

import cProfilecProfile.run(‘函数名‘)

CProfile (or profile) can print the timing results of each function.
</br>
</br>
</br>
Second, dictionary and hash hash table (hashing)
A hash table (hash table, also known as a hash list) is a data structure that is accessed directly from a key value. That is, it accesses records by mapping key code values to a location in the table to speed up lookups. This mapping function is called a hash function, and the array that holds the record is called the hash table. It can be guessed that the hash table is used for the implementation of the dictionary (dict) type and set (set) type in Python, and that our access to its elements is only a time-consuming class. The hash () function in Python is used to obtain a hash of an object (string or numeric value, etc.).
</br>
</br>
</br>
Three, the realization of the graph and the tree
Adjacency lists can be considered as representations of the graph structure.

# 举个邻接列表的栗子a, b, c, d, e, f, g, h = range(8)N = [    {b, c, d, e, f}, # a节点所指向的节点,如果想要加权则利用字典类型改为{b:2, c:1, …}    {c, e}, # b …    {d},    {e},    {f},    {c, g, h},    {f, h},    {f, g}]b in N[a]len(N[f])N[a][b]

At the same time, the adjacency matrix is also a common representation of graphs.

# 举个邻接矩阵的栗子a, b, c, d, e, f, g, h = range(8)N = [[0,1,1,1,1,1,0,0],     [0,0,1,0,1,0,0,0],     [0,0,0,1,0,0,0,0],     [0,0,0,0,0,1,0,0],     [0,0,1,0,0,0,1,1],     [0,0,0,0,0,1,0,1],     [0,0,0,0,0,1,1,0]]N[a][b] # Neighborhood membership, answer is 1sum(N[f]) # Degree, answer is 3

The way the binary tree is represented.

class Tree:    def __init__(self, left, right):        self.left = left        self.right = rightt = Tree(Tree(‘a‘, ‘b‘), Tree(‘c‘, ‘d‘))t.right.left # answer is ‘c‘

The way the multi-search tree is expressed.

class Tree:    def __init__(self, kids, next=None):        self.kids = kids        self.next = nextt = Tree(Tree(‘a‘, Tree(‘b‘, Tree(‘c‘, Tree(‘d‘)))))t.kids.next.next.kids # answer is ‘c‘

</br>
</br>
</br>
IV. member Inquiries

from random import randrangeL = [randrange(10000) for i in range(1000)]1 in L # 第一种查询操作S = set(L)1 in S # 第二种查询操作

It seems that the second query operation is superfluous, but it is necessary to know that the time spent querying members in a sequence is linear and is constant in the collection.
</br>
</br>
</br>
V. Inserting objects

# 比较两段代码# 第一段代码s = ‘‘"for chunk in string_producer():    s += chunk# 第二段代码chunks = []for chunk in string_producer():    chunks.append(chunk)s = ‘ ‘.join(chunks)

The second piece of code is a more efficient solution than the comparison. Because when we execute the first code, each time we execute "+ =", we need to create a new string and assign it a transfer property so that its time complexity is squared. Similarly, using the Extend () function is much more efficient than the sum () function when adding operations to a sequence.

Python algorithm Tutorial chapter II Knowledge Points: Timing module, dictionary and hash table, graph and tree implementation, member query, insert Object

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.