The best solution to the problem is to find the code that someone else has to solve a similar problem.
Today, do some small exercises that can look back at what you have learned, and similar questions refer to someone else's code and modify it to be easy to understand.
1, the implementation of a simple stack. The put (item) implements the data in the item insert stack, and the Get () implementation takes a data from the stack.
# -*- coding: utf-8 -*-class mystack (object): "MyStack Custom Stack, operation has 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 ())
The results of the operation are as follows:
Put a successput b successbput c successcaput error:the Stack is overflow!
2. Determine the encoding used for the specified Web page.
# -*- coding: utf-8 -*-import sysimport requestsimport chardetdef 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])
The results are as follows:
C:\>python webdetect.py http://blog.51cto.com/9473774http://blog.51cto.com/9473774 <-Utf-8c:\>python webd etect.py http://www.163.comhttp://www.163.com <-GB2312
3. Traverse all the files in the specified directory to find the top 3 files that occupy the most space.
# -*- coding: utf-8 -*-import sysimport osdef 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 ')
The results of the operation are as follows:
146313216e:\iso\centos-6.8-x86_64-bin-dvd1\images\install.img45373440e:\iso\centos-6.8-x86_64-bin-dvd1\images\ Efidisk.img40688737e:\iso\centos-6.8-x86_64-bin-dvd1\isolinux\initrd.img
"Cute Python" reading notes (eight)