day 14 - 2 generator exercise

Related exercises

1. Process the file. The user specifies the file and content to be found, and outputs each line of the file containing the content to be found to the screen

#compare low Method
def check_file(filename,aim):
    with open(filename,encoding='utf-8') as f: #handle : handler,File operators, file handles
        for line in f:
            if aim in line:
                print(line.strip())
check_file('E:/py/log/log.txt','add')


#Generator implementation
def check_file(filename,aim):
    with open(filename,encoding='utf-8') as f: #handle : handler,File operators, file handles
        for line in f:
            if aim in line:
                yield line
g = check_file('E:/py/log/log.txt','add')
for i in g:
    print(i.strip())

 

2. Write the generator to read the content from the file, add "*", and then return it to the user.

def check_file(filename):
    with open(filename,encoding='utf-8')as f:
        for i in f:
            yield '***'+i.strip()
#g = check_file("E:/py/log/log.txt")
#for i in g:
#    print(i)

#You can also write like this
for i in check_file("E:/py/log/log.txt"):
    print(i)

 

Interview questions

Interview questions related to generator

To solve the problem of the expression of the for loop generator, separate the for loop

Question 1: read the following code, what is the result of print ing?

def demo():
    for i in range(4):
        yield i
g=demo()

g1=(i for i in g)
g2=(i for i in g1)

#print(list(g)) #list() string strong conversion
print(list(g1))  #[0, 1, 2, 3]
print(list(g2))  #[]

#Why? list(g2) Will China be empty?
#Because: g1 All the values in it have been given list() When g2 Looking for g1 When it is worth, g1 It's not worth it, so g2 Return to empty

 

Question 2: read the following code, what is the result of print ing?

def add(n,i):
    return n+i

def test():
    for i in range(4):
        yield i

g=test()
for n in [1,10,5]:
     g=(add(n,i) for i in g)

print(list(g))  #[15,16,17,18]

"""
#Take the above for loop apart and replace the unknown number g with the known one
###It's very important that when n=1, n=10, the program doesn't execute, it just does the assignment, and it's gone
###When did the program start taking values? Execute only when list(g), this is the time n is the last n
###The front n's gone

n = 1
g=(add(n,i) for i in g)     #g=test()
n = 10
g=(add(n,i) for i in g)     #g=(add(n,i) for i in test()))
n = 5
g=(add(n,i) for i in g)     #g=(add(n,i) for i in (add(n,i) for i in test())))


#The combination is
n = 1
g=(add(n,i) for i in test())
n = 10
g=(add(n,i) for i in (add(n,i) for i in test()))
n = 5
g=(add(n,i) for i in add(n,i) for i in (add(n,i) for i in test()))

#The results are: g=[15,16,17,18]
"""

Tags: Python encoding

Posted on Sun, 01 Dec 2019 12:34:07 -0800 by Bijan