#保留符合要求的N个条目 from collections import deque def search(lines,pattern,history=5): previous_lines = deque(maxlen=history)#队列 for li in lines: if pattern in li: yield li,previous_lines#找到pattern,并yield previous_lines.append(li)#入队列 #Example use om s file if __name__ == '__main__': with open(r'/etc/passwd')as f:#被查找文件 for line,prevlines in search(f,'root',6): for pline in prevlines:#输出队列 print(pline,end='') print('-'*20)
#括号匹配 stack = [] for c in exp: if c in (t[0] for t in brackets):#依次找到所有左括号,并入栈 stack.append(c) elif c in (t[1] for t in brackets):#判断右括号 if not len(stack): print('Error')#栈空,则不匹配 break left = stack.pop()#找到栈顶元素所匹配的右括号 bs = [t[1] for t in brackets if t[0] == left] if bs[0] != c:#判断栈顶右括号是否与当前右括号相匹配 print('Error') break else: if len(stack):#栈空,则匹配 print('Error') else: print('Ok')
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。