可爱的Python_课后习题_CDay−2 完成核心功能

1. 在前文的grep 实现例子中,没有考虑子目录的处理方式,因为如果直接open 目录进行读grep 是古老实用且高效的模式文本匹配工具,在所有的Unix/Linux 系统中都会默认安装,它最常做的事儿是将一堆文本中包含某个模式的文本行找出来,如:~$ cat /proc/cpuinfo | grep

core
core id :0
cpu cores :2
core id :1
cpu cores :2
30 | 实例故事操作,会出现错误,所以请读者修改这个示例代码,以便考虑到子目录这种特殊情况,然后把最后探索出的 cdcGrep()嵌入 pycdc-v0.5.py 中,实现完成版本的PyCDC。

python代码:

def grep(cdcpath, keyword):
    cdcpathlist = list()
    index  = 1

    for root, dirs, files in os.walk(cdcpath):
        for file in files:
            if ".txt" in file:
                cdcpathlist.append(os.path.join(root, file))

    for cdcpath in cdcpathlist:
        cdcfile = open(cdcpath)
        for line in cdcfile.readlines():
            if keyword in line:
                print line

 

2. 编写一个类,实现简单的栈。数据的操作按照先进后出(FILO)的顺序。主要成员 函式为 put(item),实现数据 item 插入栈中;get(),实现从栈中取一个数据。 

python代码:

#encoding=utf-8

class Stack:
    items = list()

    def put(self, item):
        self.items.append(item)


    def get(self):
        length = len(self.items)
        item = self.items[length-1]
        self.items.remove(item)
        return item


if __name__ == "__main__":
    stack = Stack()
    for item in range(1, 10):
        stack.put(item)

    for item in range(1, 10):
        print stack.get()

 

转载于:https://www.cnblogs.com/zhuhaiying/p/6208469.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值