问题的最佳的解决方案,就是找到那段别人解决相似问题的代码。
今天做些能回顾所学知识点的小练习,类似的问题参考别人的代码,修改成自己容易理解的模样。
1、实现简单的栈。put(item)实现数据item插入栈中;get()实现从栈中取一个数据。
# -*- coding: utf-8 -*- class MyStack(object): '''MyStack 自定义栈,操作有put(), get() ''' def __init__(self): self.head = -1 self.stack = [] def put(self, item): self.head += 1 self.stack.append(item) print('Put %s Success' % item) def get(self): if self.head < 0: return "Put Error: The Stack is Overflow!" else: self.head -= 1 return self.stack.pop() def isEmpty(self): return self.item == [] if __name__ == "__main__": mystack = MyStack() mystack.put('a') mystack.put('b') print(mystack.get()) mystack.put('c') print(mystack.get()) print(mystack.get()) print(mystack.get())
运行结果如下:
Put a Success Put b Success b Put c Success c a Put Error: The Stack is Overflow!
2、判断指定网页使用的编码。
# -*- coding: utf-8 -*- import sys import requests import chardet def web_detect(url): #检测网页的编码方式 try: response = requests.get(url) except: print('error') return 0 web= response.content response.close() codedetect = chardet.detect(web)["encoding"] print('%s\t<-\t%s' % (url, codedetect)) return 1 if __name__ == '__main__': if len(sys.argv) == 1: print('usage:\n\tpython XX.py http://xxx.com') else: web_detect(sys.argv[1])
运行效果如下:
C:\>python webdetect.py http://blog.51cto.com/9473774 http://blog.51cto.com/9473774 <- utf-8 C:\>python webdetect.py http://www.163.com http://www.163.com <- GB2312
3、遍历指定目录下的所有文件,找出其中占用空间最大的前3个文件。
# -*- coding: utf-8 -*- import sys import os def get_top_three(path): d = {} for root, dirs, files in os.walk(path): for file in files: fname = os.path.join(root, file) fsize = os.stat(fname).st_size d[fname] = fsize #print(d) f = sorted(zip(d.values(), d.keys())) for i in [-1, -2, -3]: for j in f[i]: print(j) get_top_three('E:\\iso\\CentOS-6.8-x86_64-bin-DVD1')
运行结果如下:
146313216 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\install.img 45373440 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\efidisk.img 40688737 E:\iso\CentOS-6.8-x86_64-bin-DVD1\isolinux\initrd.img
原文地址:http://blog.51cto.com/9473774/2091006
时间: 2024-10-11 06:01:45