# Python算法教程第二章知识点：计时模块、字典与散哈希表、图与树的实现、成员查询、插入对象

import timeit
timeit.timeit('x = 1 + 2')

import cProfile
cProfile.run('函数名'）

cProfile（或profile）能够将各函数的计时结果打印出来。

# 举个邻接列表的栗子

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]

# 举个邻接矩阵的栗子

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 1
sum(N[f]) # Degree, answer is 3

class Tree：
def __init__(self, left, right):
self.left = left
self.right = right

t = Tree(Tree('a', 'b'), Tree('c', 'd'))
t.right.left # answer is 'c'


class Tree:
def __init__(self, kids, next=None):
self.kids = kids
self.next = next

t = Tree(Tree('a', Tree('b', Tree('c', Tree('d')))))
t.kids.next.next.kids # answer is 'c'

from random import randrange
L = [randrange(10000) for i in range(1000)]

1 in L # 第一种查询操作

S = set(L)
1 in S # 第二种查询操作


# 比较两段代码

# 第一段代码
s = ''
for chunk in string_producer():
s += chunk

# 第二段代码
chunks = []
for chunk in string_producer():
chunks.append(chunk)
s = ' '.join(chunks)