协程函数、递归调用

1、消费者生产者模型初级

2、获取指定目录下子目录与文件

3、递归调用

 

--消费者生产者模型初级

def eater(name):
    print('%s start to eat' %name )
    while True:
        food = yield
        print('%s eat %s' %(name,food))
        
        
alex_g = eater('alex')#先获得生成器
next(alex_g)#触发函数使函数暂停到函数的yield
alex_g.send('骨头')#给yield发送个值,使yield赋值给food,然后执行函数

 


--#改进使其能交互,并使生产者获取清单保存消费项目

def eater(name):
    food_list =[]
    print('%s start to eat' %name )
    while True:
        food = yield food_list
        food_list.append(food)
        print('%s eat %s' %(name,food))

def producter():
    alex_g = eater('alex')  # 先获得生成器
    next(alex_g)  # 触发函数使函数暂停到函数的yield
    while True:
        inp = input('>>>')
        print(alex_g.send(inp))#给yield发送个值,使yield赋值给food,然后执行函数
producter()

 

--改进使初始化咋装饰器中进行

def init(func):
    def wapper(*args,**kwargs):
        alex_g = func(*args,**kwargs)  # 先获得生成器
        next(alex_g)  # 触发函数使函数暂停到函数的yield
        return alex_g
    return wapper

@init
def eater(name):
    food_list =[]
    print('%s start to eat' %name )
    while True:
        food = yield food_list
        food_list.append(food)
        print('%s eat %s' %(name,food))

def producter():
    g = eater('alex')#调用eater函数--》装饰器执行func(alex)获得生成器--》使暂停到eater的yield--》执行装饰器中初始化--》将生成器返回给g
    while True:
        inp = input('>>>')
        print(g.send(inp))#给yield发送个值,使yield赋值给food,然后执行函数
producter()

 

--获取指定目录下子目录与文件

import os
t = os.walk(r'C:\Users\liguangxu\PycharmProjects\untitled2')#这里会获得一个迭代器
print(next(t))
#获得该目录下的子目录与文件,元组的第一个元素为指定目录,第二个元素为目录下的文件夹,第三个元素为指定目录的文件
#('C:\\Users\\liguangxu\\PycharmProjects\\untitled2', ['.idea', '111', 'day3', 'day4', 'day5'], [])
print(next(t))
#第一个元素为第一个指定目录下的文件夹,第二个元素为第一个指定目录下的文件夹下的文件夹,第三个为指定目录下的第一个目录下的文件
#('C:\\Users\\liguangxu\\PycharmProjects\\untitled2\\.idea', [], ['misc.xml', 'modules.xml', 'untitled2.iml', 'workspace.xml'])
#想要获取指定目录下的所有文件的绝对路径的方法
import os
t = os.walk(r'C:\Users\liguangxu\PycharmProjects\untitled2')
for pardir,_,files in t:#将第一个元素(目录)和第三个元素(目录下的文件)拿到做拼接
for file in files:
abspath = r'%s\%s'%(pardir,file)
print(abspath)

 

--递归调用
#递归调用:在调用一个函数的过程中,直接或者间接的调用了函数本身
#效率低,必须有一个明确的结束条件,没进入更深一层递归时,问题规模相比上一次递归减少
#查看递归层级 sys.getrecursionlimit() 修改递归层级 sys.getrecursionlimit()

def  age(n):
    if n == 1:
        return 18
    return age(n-1)+2
print(age(5))

l = [1,2,[3,4,5,6,[7,8,9,[10,11,12]]]]
def li(l):
    for item in l:
        if type(item) is list:
            li(item)
        else:
            print(item)
    

 

转载于:https://www.cnblogs.com/kunixiwa/p/7267988.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值