- 피보나치 수는 0과 1로 시작하며, 다음 피보나치 수는 바로 앞의 두 피보나치 수의 합이 된다. n = 0, 1,...에 해당하는 피보나치 수는

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946... 이다.


제너레이터

참고: http://bluese05.tistory.com/56

참고: https://mingrammer.com/translation-iterators-vs-generators

참고: https://www.snip2code.com/Snippet/1571818/yield-send---generator------example


일단적인 함수는 사용이 종료되면 결과값을 호출부로 반환 후 함수 자체를 종료시킨 후 메모리 상에서 클리어된다 

하지만 yield 를 사용할 경우는 다르다.

generator 함수가 실행 중 yield 를 만날 경우, 해당 함수는 그 상태로 정지 되며 반화값을 next() 를 호출한 쪽으로 전달하게 된다.

이후 해당 함수는 일반적인 함수처럼 종료되고 메로리상에서 클리어되는게 아니라 그 yield 를 만나 시점의 상태로 유지되게 된다.

즉 함수에서 사용된 local 변수나 instrunction pointer 긍과 같은 함수 내부에서 사용된 데이터들이 메모리에 그대로 유지되는것이다.



def fib():

    past_num, curr_num = 0, 1

    while 1:

        yield curr_num

        past_num, curr_num = curr_num, past_num + curr_num


>> f = fib()

>> f.next()

1

>> f.next()

1

>> f.next()

2

>> f.next()

3

>> f.next()

5

>> f.next()

8


>>> from itertools import islice

>>> f = fib()      

>>> list(islice(f, 1, 10))

[1, 2, 3, 5, 8, 13, 21, 34, 55]

>>> f.next()

89



피보나치 수를 제너레이터로 구현한거


>>> def index_words_iter(text):

...     if text:

...         yield 0

...     for index, letter in enumerate(text):

...         if letter == ' ':

...             yield index + 1

... 

>>> 

>>> list(index_words_iter(address))

[0, 5, 11, 15, 21, 27, 31]

>>> 

>>> 

>>> f = index_words_iter(address)

>>> 

>>> f.next()

0

>>> f.next()

5

>>> f.next()

11

>>> f.next()

15

>>> f.next()

21

>>> f.next()

27

>>> f.next()

31

>>> f.next()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

StopIteration


list 롤 감싸게 되면 StopIteration 발생하면 리턴해주는가부네 




'TF' 카테고리의 다른 글

[Research] Django  (0) 2017.06.29
[Research] API gateway  (0) 2017.06.29
[Research] microservice  (0) 2017.06.29
[Research] django high availability  (0) 2017.06.28
[Research] openstack  (0) 2017.06.27

+ Recent posts