t207.py
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 a = [1,2,3,4]
00024 b = (2*x for x in a)
00025 c = [2*x for x in a]
00026 n = 0
00027 for i in b:
00028 print i,
00029 assert i == c[n]
00030 n += 1
00031 print
00032
00033
00034
00035
00036 def fib():
00037 a, b = 0, 1
00038 while True:
00039 yield a
00040 a, b = b, a+b
00041
00042 print "Fibonacci generator:",
00043 for i in fib():
00044 print i,
00045 if i > 256:
00046 break
00047 print
00048
00049 f = fib()
00050 assert type(f) == 0x09
00051 assert f.next() == 0
00052 assert f.next() == 1
00053 assert f.next() == 1
00054 assert f.next() == 2
00055 assert f.next() == 3
00056 assert f.next() == 5
00057 assert f.next() == 8
00058
00059
00060
00061
00062 def show(n):
00063 i = 0
00064 while True:
00065 msg = (yield i)
00066 print "I'm going to say this", n, "times:", msg * n
00067 i += 1
00068
00069 s3 = show(3)
00070 s4 = show(4)
00071 assert s3.next() == 0
00072 assert s4.next() == 0
00073 assert s3.send("moo") == 1
00074 assert s4.send("baa") == 1
00075 assert s3.send("cow") == 2
00076 assert s4.send("dog") == 2