In [1]:
def sub_routine():
    return 10
In [2]:
def co_routine():
    yield 10
    yield 20
    yield 30
In [3]:
sub_routine()
Out[3]:
10
In [4]:
co_routine()
Out[4]:
<generator object co_routine at 0x03696120>
In [5]:
generator1=co_routine()
In [6]:
generator1
Out[6]:
<generator object co_routine at 0x035C9390>
In [7]:
next(generator1)
Out[7]:
10
In [8]:
next(generator1)
Out[8]:
20
In [9]:
next(generator1)
Out[9]:
30
In [10]:
next(generator1)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-10-1e26bff1d0c7> in <module>()
----> 1 next(generator1)

StopIteration: 
In [11]:
for i in generator1:
    print(i)

피보나치 수열 예제

In [14]:
def fib(max_count):
    ''' 소비자가 최대 개수를 함수 설정시 정함'''
    x, y, count=1, 1, 0
    while True:
        if count>= max_count:
            break
        yield x
        x, y = y, x+y
        count += 1
In [16]:
for x in fib(10):
    print(x, end=",")
1,1,2,3,5,8,13,21,34,55,
In [17]:
def confib():
    ''' 소비자가 최대 크기를 함수를 이용한 반복문 설정시 설정함 (더 범용적)'''
    x,y= 1,1
    while True :
        yield x
        x,y=y,x+y
In [20]:
count=0
for x in confib():
    print(x,end=",")
    count+=1
    if count >10 :
        break
1,1,2,3,5,8,13,21,34,55,89,
In [21]:
count=0
for x in confib():
    print(x,end=",")
    count+=1
    if count >10 :
        break
1,1,2,3,5,8,13,21,34,55,89,
In [22]:
from itertools import islice
In [23]:
islice(confib(),10)
Out[23]:
<itertools.islice at 0x3858840>
In [25]:
list(islice(confib(),10))
Out[25]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Comprehension과 제너레이터 표현식

In [26]:
[i**2 for i in range(5)]
Out[26]:
[0, 1, 4, 9, 16]
In [27]:
[i**2 for i in fib(10)]
Out[27]:
[1, 1, 4, 9, 25, 64, 169, 441, 1156, 3025]
In [29]:
{i**2 for i in range(10) if i%2==0}
Out[29]:
{0, 4, 16, 36, 64}
In [30]:
(i**2 for i in range(100))
Out[30]:
<generator object <genexpr> at 0x038586F0>
In [32]:
list(i**2 for i in range(100))
Out[32]:
[0,
 1,
 4,
 9,
 16,
 25,
 36,
 49,
 64,
 81,
 100,
 121,
 144,
 169,
 196,
 225,
 256,
 289,
 324,
 361,
 400,
 441,
 484,
 529,
 576,
 625,
 676,
 729,
 784,
 841,
 900,
 961,
 1024,
 1089,
 1156,
 1225,
 1296,
 1369,
 1444,
 1521,
 1600,
 1681,
 1764,
 1849,
 1936,
 2025,
 2116,
 2209,
 2304,
 2401,
 2500,
 2601,
 2704,
 2809,
 2916,
 3025,
 3136,
 3249,
 3364,
 3481,
 3600,
 3721,
 3844,
 3969,
 4096,
 4225,
 4356,
 4489,
 4624,
 4761,
 4900,
 5041,
 5184,
 5329,
 5476,
 5625,
 5776,
 5929,
 6084,
 6241,
 6400,
 6561,
 6724,
 6889,
 7056,
 7225,
 7396,
 7569,
 7744,
 7921,
 8100,
 8281,
 8464,
 8649,
 8836,
 9025,
 9216,
 9409,
 9604,
 9801]
In [ ]: