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 88 89 90 91 92 93 94 95 96
| def counter(): i = 0 while True: i += 1 yield i def inc(c): return next(c) c = counter() print(inc(c)) print(inc(c)) 输出: 1 2
def counter(): i = 0 while True: i += 1 yield i def inc(): c = counter() return next(c)
print(inc()) print(inc()) print(inc()) 输出: 1 1 1
def inc(): def counter(): i = 0 while True: i += 1 yield i c = counter() return lambda:next(c) foo = inc() print(foo()) print(foo())
def inc(): def counter(): i = 0 while True: i += 1 yield i c = counter() def _inc(): return next(c) return _inc
foo = inc() print(foo()) print(foo()) print(foo())
def fib(): x = 0 y = 1 while True: yield y x,y = y,x+y foo = fib() for _ in range(5): print(next(foo)) for _ in range(100): next(foo) print(next(foo))
pre = 0 cur = 1 print(pre,cur,end=' ')
def fib1(n,pre=0,cur=1): pre,cur = cur,pre+cur print(cur,end=' ') if n == 2: return fib1(n-1,pre,cur)
|