Python builder and iterator (yield usage)

Source: Internet
Author: User

Background

First of all, I will not explain the two nouns, I have read many times to explain, but still do not understand, or directly see the use of the scene.
We take the Pepolaci sequence as an example, and when we don't know the iterator, the code we write might be like this:

‘‘‘这种方式计算fib(100)都很吃力‘‘‘fib = lambda n:fib(n-2) + fib(n-1) if n>1 else 1

or optimize it and become like this:

‘‘‘将迭代结果存入temp中,避免重复的计算, 这样可以提高计算速度,但是当计算fib(4000)时,会报:“maximum recursion depth exceeded in comparison”也就是说会超过最大迭代次数‘‘‘temp = {}def fib(n):    if n in temp:        return temp[n]        if n>1:        _t = fib(n-1) +  fib(n-2)        temp[n] = t        return _t    else:        return 1

Given the further optimizations, we need to introduce the yield syntax of Python

Use yield

The use of yield is simply to return the yield run result, and when __next__ is called, it runs to yield again and returns . So we can take advantage of this feature, so that the FIB function returns only the current and previous values at a time, updates both values when it runs again, and returns just fine. The following code is then available:

‘‘‘这次我们可以最大程度发挥计算机性能,比上个版本能计算的更多也更快(我电脑能计算6位数的fib值)‘‘‘def fib_gen():    ‘‘‘    这时一个佩波拉契数列的生成器,每次迭代返回当前值和前一个的值    ‘‘‘    c , p = 1,1    while True:        yield p # 每次next运行到此,并返回p的值。当再次调用时,继续执行下面代码,        p, c = c, c+p # 计算下次p的值        def fib(n):    ‘‘‘根据情况不断运行next(f),直到适合的条件‘‘‘    f = fib_gen()    for i in range(n+1):        cur = next(f)    return n

We're looking at an example of a simple generator.

In [1]: array = [1,2,3,4]In [2]: f = (i for i in array) # 是不是看起来很像“元组推倒式”,其实这是一个生成器。python并没有元组的推倒式In [3]: f # 不信,我们来实际看看Out[3]: <generator object <genexpr> at 0x10882df10>In [4]: [i for i in f] # 生成器是可以迭代的,所以列表推到能取出值Out[4]: [1, 2, 3, 4]In [5]: [i for i in f]Out[5]: [] # 此时,f中的数据全部取出,调用next(f) 取不出来值了
Summarize
    • From this example we can find that when the yield is used, the function is not executed immediately, but when we call next, we take out the value, and when it is not called, it is just a generator. Equivalent to saving the last run of the site.
    • When next is called, the yield return is not found, it is terminated, and the stopiteration error is reported, this is a dead loop in this case, and this does not happen. Interested can try to while True change it into while p < 100 something like that.

Python builder and iterator (yield usage)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.