-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpy_Generator.py
87 lines (73 loc) · 1.79 KB
/
py_Generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
g = [ i * 3 for i in range(10) ]
print(g)
g = ( i * 3 for i in range(10) )
print(g)
print( next (g) )
print( next (g) )
print( next (g) )
print( next (g) )
print('------define yield.')
def gtr(n):
for i in range(n):
yield i
r=gtr(3)
print(next(r))
print(next(r))
print(next(r))
#print(next(r))
print('------define yield test.')
def test():
n = 0
while True:
if n < 3:
yield n
n += 1
else:
yield 10
t=test()
for i in range(6):
print(next(t))
print('------define yield from.')
def g1():
yield range(5)
def g2():
yield from range(5)
it1=g1()
it2=g2()
print('----yield:')
for x in it1:
print(x)
print('----yield from:')
for x in it2:
print(x)
# 最后,我们来看一个yield from使用的一个经典场景:二叉树的遍历:
print('binary tree:')
class Node:
def __init__(self,key):
self.key=key
self.lchild=None
self.rchild=None
self.iterated=False
self.father=None
def iterate(self):
if self.lchild is not None:
yield from self.lchild.iterate()
print(self.key)
yield self.key
if self.rchild is not None:
yield from self.rchild.iterate()
class Tree:
def __init__(self):
self.root=Node(4)
self.root.lchild=Node(3)
self.root.lchild.father=self.root
self.root.rchild=Node(5)
self.root.rchild.father=self.root
self.root.lchild.lchild=Node(1)
self.root.lchild.lchild.father=self.root.lchild
self.root.rchild.rchild=Node(7)
self.root.rchild.rchild.father=self.root.rchild
def iterate(self):
yield from self.root.iterate()
T=Tree()
T.iterate()