zoukankan      html  css  js  c++  java
  • python生成器 递归

    生成器

    生成器:只要函数体内出现yield关键字,那么再执行函数就不会执行函数代码,会得到一个结果,该结果就是生成器
     
    生成器就是迭代器
     
    yield的功能
    1、yield为我们提供了一种自定义迭代器对象的方法
    2、yield于return的区别:
    1)yield可以返回多个值 
    2)函数暂停和再继续是由yield帮我们保存的
     
    def test():
         print('=== >1')
         yield 1
         print('=== >2')
         yield 2
         print('===>3')
         yield 3
    g = test()     #print里的值由yield保存
    for i in g:         
         print(i)   
          
            
     
    def test1():
         for i in range(10):
             yield i                 
    g = test1()
    def test2(g):      #调用生成器
         for i in g:
             print(i)
    test2(g)
     

    #监控日志

    import  time
    def tail(filepath):   #定义一个查看文件的函数
        with open(filepath,'rb') as f:  #以二进制的形式打开filepath
             f.seek(0,2)
             while True:  #循环监控日志
                data = f.readline()  #读取文件末尾
                 if data:  #加入有数据就用yield返回
                     yield data
                else: #否则睡眠0.05秒
                     time.sleep(0.05)
    def grep(file,k): #定义过滤关键字函数
        for i in tail(file):  #循环生成器中的数据
             if k in i.decode('utf-8'):  #因为是用二进制服务方式,所有需要解码显示
                print(i.decode('utf-8'))   #
    grep('a.txt',404) #监控a.txt最新日志,并过虑404的错误代码
     
     

    yield赋值

    def test(name):
         while True:
            foot = yield
            print('%s正在吃%s' %(name,foot))
     
    e = test('1807')
    next(e)      #初始化 e._next_()
    e.send(None)    #初始化
    e.send('choudoufu')  #发送值传给foot
    e.send('冰激凌')
     
     

    递归调用:在调用一个函数的过程中,直接或者间接又调用了函数本身,称之为递归调用

    递归必备的2个阶段:
    1递归
     2 回溯
     
     age(5) = age(4) + 2
    age(4) = age(3) + 2
     age(3) = age(2) + 2
     age(2) = age(1) + 2
     age(1) = 0
     
    def love(n):
        if n == 1:
            return 0
        return love(n-1) + 2
    res = love(5)
    print(res)
  • 相关阅读:
    杭电2048--神、上帝以及老天爷
    杭电1012--u Calculate e
    杭电2049--不容易系列之(4)——考新郎
    杭电2045--不容易系列之(3)—— LELE的RPG难题
    Truncate Table user
    Sql server统计查询语句消耗时间
    C/C++:Unions 联合
    NYOJ 27 水池数目
    OpenRisc-39-ORPSoC,or1200的memory hierarchy整体分析
    RCP打包出来 运行 出现 JVM terminated.exit code = 13
  • 原文地址:https://www.cnblogs.com/heiguu/p/10048803.html
Copyright © 2011-2022 走看看