zoukankan      html  css  js  c++  java
  • 生成器相关的面试题

     1 def demo():
     2     for i in range(4):
     3         yield i
     4 
     5 g=demo()
     6 
     7 g1=(i for i in g)
     8 g2=(i for i in g1)
     9 
    10 print(list(g1))
    11 print(list(g2))
    1
     1 def add(n,i):
     2     return n+i
     3 
     4 def test():
     5     for i in range(4):
     6         yield i
     7 
     8 g=test()
     9 for n in [1,10]:
    10     g=(add(n,i) for i in g)
    11 
    12 print(list(g))
    2
     1 def add(n,i):
     2     return n+i
     3 
     4 def test():
     5     for i in range(4):
     6         yield i
     7 
     8 g=test()
     9 for n in [1,10]:
    10     g=(add(n,i) for i in g)
    11 
    12 print(list(g))
    13 
    14 复制代码
    15 
    16  
    17 
    18 复制代码
    19 import os
    20 
    21 def init(func):
    22     def wrapper(*args,**kwargs):
    23         g=func(*args,**kwargs)
    24         next(g)
    25         return g
    26     return wrapper
    27 
    28 @init
    29 def list_files(target):
    30     while 1:
    31         dir_to_search=yield
    32         for top_dir,dir,files in os.walk(dir_to_search):
    33             for file in files:
    34                 target.send(os.path.join(top_dir,file))
    35 @init
    36 def opener(target):
    37     while 1:
    38         file=yield
    39         fn=open(file)
    40         target.send((file,fn))
    41 @init
    42 def cat(target):
    43     while 1:
    44         file,fn=yield
    45         for line in fn:
    46             target.send((file,line))
    47 
    48 @init
    49 def grep(pattern,target):
    50     while 1:
    51         file,line=yield
    52         if pattern in line:
    53             target.send(file)
    54 @init
    55 def printer():
    56     while 1:
    57         file=yield
    58         if file:
    59             print(file)
    60 
    61 g=list_files(opener(cat(grep('python',printer()))))
    62 
    63 g.send('/test1')
    64 
    65 协程应用:grep -rl /dir
    3
  • 相关阅读:
    初识sed和gwak
    USB驱动程序设计
    linux-usb软件系统架构
    CSS基础 布局
    CSS基础 样式属性
    CSS基础 样式分类、选择器
    HTML基础 页面效果(标题图标、锚点、插入音乐,视频、滚动效果、嵌入网页)
    HTML基础 常用标记
    HTML基础 表单
    HTML基础 初识 HTML(整体结构 文字 图片 表格 超链接)
  • 原文地址:https://www.cnblogs.com/haiyan123/p/7280310.html
Copyright © 2011-2022 走看看