ZIP Archive Files. The unzip -l command to dump the contents of ZIP archive is boring. Create a Python script called lszip.py that gives additional information such as: the compressed file size, the compressed percentage of each file (by comparing the original and compressed file sizes), and a full time.ctime() timestamp instead of the unzip output (of just the date and HH:MM). Hint: The date_time attribute of an archived file does not contain enough information to feed to time.mktime()... it is up to you!
#!/usr/bin/env python #-*- coding:utf-8 -*- #$Id: p0922.py 168 2010-06-29 06:34:01Z xylz $ ''' This is a 'python' study plan for xylz. Copyright (C)2010 xylz (www.imxylz.info) ''' import zipfile import os import datetime def list (zip_file,files): print"list %s files from %s"% (len(files) if files!='*'else'total',zip_file) f_in = zipfile.ZipFile(zip_file, 'r') infoes = None if'*'== files: infoes = f_in.infolist() else: infoes = [] for f in files: infoes.append(f_in.getinfo(f)) print"filename:\t\tuncompress\tcompress\tpercent\tcreatetime" print"-----------------------------------------" total_usize,total_csize = (0,0) for info in infoes: (year, month, day, hour, minute, second) = info.date_time dtime = datetime.datetime(year, month, day, hour, minute, second) filename,usize,csize = info.filename,info.file_size,info.compress_size print"%s:\t\t%d\t%d\t%d%%\t%s"% (filename,usize,csize,(csize*100/(usize+0.01)),dtime.ctime()) total_usize += usize total_csize += csize f_in.close() print"-----------------------------------------" print"compressed size %d bytes, uncompressed size %d bytes, %d%%"% (total_csize,total_usize,(total_csize*100/total_usize)) if__name__=='__main__': import sys if len(sys.argv)<2: print"List files in zip file" print"Usage: %s <zipfile> [files]"% (sys.argv[0],) sys.exit(0) zip_file = sys.argv[1] files ='*' if len(sys.argv)>2: files = [] for f in sys.argv[2:]: files.append(f) list(zip_file,files)
]]>Core Python Programming Exercises P09-20http://www.tkk7.com/xylz/articles/324759.htmlxylzxylzTue, 29 Jun 2010 03:51:00 GMThttp://www.tkk7.com/xylz/articles/324759.htmlhttp://www.tkk7.com/xylz/comments/324759.htmlhttp://www.tkk7.com/xylz/articles/324759.html#Feedback0http://www.tkk7.com/xylz/comments/commentRss/324759.htmlhttp://www.tkk7.com/xylz/services/trackbacks/324759.html
9-20.
Compressed Files. Write a short piece of code that will compress and decompress gzipped or bzipped files. Confirm your solution works by using the command-line gzip or bzip2 programs or a GUI program like PowerArchiver, StuffIt, and/or WinZip.
]]>Core Python Programming Exercises P07-10http://www.tkk7.com/xylz/articles/324056.htmlxylzxylzMon, 21 Jun 2010 04:25:00 GMThttp://www.tkk7.com/xylz/articles/324056.htmlhttp://www.tkk7.com/xylz/comments/324056.htmlhttp://www.tkk7.com/xylz/articles/324056.html#Feedback0http://www.tkk7.com/xylz/comments/commentRss/324056.htmlhttp://www.tkk7.com/xylz/services/trackbacks/324056.html7-10. Encryption. Using your solution to the previous problem, and create a "rot13" translator. "rot13" is an old and fairly simplistic encryption routine whereby each letter of the alphabet is rotated 13 characters. Letters in the first half of the alphabet will be rotated to the equivalent letter in the second half and vice versa, retaining case. For example, a goes to n and X goes to K. Obviously, numbers and symbols are immune from translation.
(b) Add an application on top of your solution to prompt the user for strings to encrypt (and decrypt on reapplication of the algorithm), as in the following examples:
% rot13.py
Enter string to rot13: This is a short sentence.
Your string to en/decrypt was: [This is a short
sentence.].
The rot13 string is: [Guvf vf n fubeg fragrapr.].
%
% rot13.py
Enter string to rot13: Guvf vf n fubeg fragrapr.
Your string to en/decrypt was: [Guvf vf n fubeg
fragrapr.].
The rot13 string is: [This is a short sentence.].
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0710.py 153 2010-06-21 04:19:15Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10endic = None 11ifnot endic: 12 endic = {} 13import string 14for cc in (string.lowercase,string.uppercase): 15for i,c in enumerate(cc): 16if i<13: endic[c]=cc[i+13] 17else: endic[c]=cc[i-13] 18 19def encrypt_decrypt(s): 20 ret=[] 21for c in s: 22 ret.append(endic.get(c,c)) 23return"".join(ret) 24 25if__name__=='__main__': 26while True: 27 my_input = raw_input('Enter string to rot13: ') 28ifnot my_input: break 29print"Your string to en/decrypt was: [",encrypt_decrypt(my_input),"]." 30
(1)Create a function called findchr(), with the following declaration:
def findchr(string, char)
findchr() will look for character char in string and return the index of the first occurrence of char, or -1 if that char is not part of string. You cannot use string.*find() or string.*index() functions or methods.
(2)Create another function called rfindchr() that will find the last occurrence of a character in a string. Naturally this works similarly to findchr(), but it starts its search from the end of the input string.
(3)Create a third function called subchr() with the following declaration:
def subchr(string, origchar, newchar)
subchr() is similar to findchr() except that whenever origchar is found, it is replaced by newchar. The modified string is the return value.
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0612.py 140 2010-05-27 04:10:06Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10 11def findchr(s,ch): 12""" 13 Look for character 'ch' in 's' and return the index of the first occurrence of 'ch', or -f if that 'ch' is not part of 's' 14""" 15if s is None or len(s)==0: return-1 16for i,c in enumerate(s): 17if c == ch: return i 18return-1 19 20def rfindchr(s,ch): 21""" 22 Look for character 'ch' in 's' and return the index of the last occurrence of 'ch', or -f if that 'ch' is not part of 's' 23""" 24if s is None or len(s)==0: return-1 25for i in range(len(s)-1,-1,-1): 26if s[i] == ch: return i 27return-1 28 29def subchr(s,oldch,newch): 30""" 31 Look for character 'oldch' in 'newch' and replace each 'oldch' with 'newch' and return the string modified. 32""" 33if s is None or len(s)==0: return s 34 ret=[] 35for c in s: 36 ret.append(c if c!=oldch else newch) 37return''.join(ret) 38 39 40if__name__=='__main__': 41assert1== findchr('Good','o') 42try: 43assert 0 == findchr('Good','x') 44raise ValueError, 'Test fail.' 45except AssertionError as e: 46print e 47assert2== rfindchr('Good','o') 48assert'Gxxd'== subchr('Good','o','x') 49 50
]]>Core Python Programming Exercises P06-11http://www.tkk7.com/xylz/articles/321998.htmlxylzxylzThu, 27 May 2010 03:42:00 GMThttp://www.tkk7.com/xylz/articles/321998.htmlhttp://www.tkk7.com/xylz/comments/321998.htmlhttp://www.tkk7.com/xylz/articles/321998.html#Feedback0http://www.tkk7.com/xylz/comments/commentRss/321998.htmlhttp://www.tkk7.com/xylz/services/trackbacks/321998.html
6-11. Conversion.
Create a program that will convert from an integer to an Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ.
Update your program to be able to do the vice versa of the above.
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0611.py 139 2010-05-21 09:45:30Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10def convertIp2Str(ip): 11return'.'.join( ( str((ip>>i) &0xFF) for i in (24,16,8,0)) ) 12 13def convertStr2Ip(s): 14 r=0 15for i,v in enumerate(s.split('.')): 16 r |= ( int(v) << (24-i*8)) 17return r 18 19 20if__name__=='__main__': 21''' 22 Convert ip from Integer number to string and do it versa. 23''' 24 sip ='192.168.1.1' 25 ip = convertStr2Ip(sip) 26 sip2 = convertIp2Str(ip) 27print sip,ip,sip2
]]>Core Python Programming Exercises P06-10http://www.tkk7.com/xylz/articles/321558.htmlxylzxylzFri, 21 May 2010 09:14:00 GMThttp://www.tkk7.com/xylz/articles/321558.htmlhttp://www.tkk7.com/xylz/comments/321558.htmlhttp://www.tkk7.com/xylz/articles/321558.html#Feedback0http://www.tkk7.com/xylz/comments/commentRss/321558.htmlhttp://www.tkk7.com/xylz/services/trackbacks/321558.html6-10.
Strings. Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string.
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0610.py 138 2010-05-21 09:10:35Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10import string 11 12_letters = string.ascii_letters 13_map = dict(zip(_letters,_letters[26:52]+_letters[0:26])) 14 15def caseInverted(s): 16if s is None or len(s) ==0: return s 17 r=[] 18for c in s: 19 r.append(_map.get(c,c)) 20return''.join(r) 21 22if__name__=='__main__': 23''' 24 Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string. 25''' 26print caseInverted('Mr.Liu') 27
String Identifiers. Modify the idcheck.py script in Example 6-1 such that it will determine the validity of identifiers of length 1 as well as be able to detect if an identifier is a keyword. For the latter part of the exercise, you may use the keyword module (specifically the keyword.kwlist list) to aid in your cause.
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0602.py 131 2010-04-21 14:20:10Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10import string 11import keyword 12 13''' 14''' 15 16alphas = string.letters +'_' 17nums = string.digits 18alphas_nums = alphas+nums 19kwlist = keyword.kwlist 20 21def isPythonId(s): 22ifnot s: return False 23ifnot len(s): return False 24if s[0] notin alphas: return False 25for c in s: 26if c notin alphas_nums: return False 27if s in kwlist: return False 28return True 29 30if__name__=='__main__': 31''' 32 String Identifiers. Modify the idcheck.py script in Example 6-1 such that it will determine the validity of identifiers of length 1 as well as be able to detect if an identifier is a keyword. For the latter part of the exercise, you may use the keyword module (specifically the keyword.kwlist list) to aid in your cause. 33''' 34while True: 35 myInput = raw_input("Identifier to test? ('exit' for over).\n>>>") 36if myInput =='exit':break 37if isPythonId(myInput): 38print"'%s' is a valid id"% myInput 39else: 40print"'%s' is an invalid id"% myInput 41 42
6-3. Sorting.
Enter a list of numbers and sort the values in largest-to-smallest order.
Do the same thing, but for strings and in reverse alphabetical (largest-to-smallest lexicographic) order.
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0603.py 132 2010-04-25 10:22:05Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10 11''' 12''' 13 14 15if__name__=='__main__': 16''' 17''' 18 nums=[] 19while True: 20 myInput = raw_input("Enter an Integer ('exit' for over).\n>>>") 21if myInput =='exit':break 22try: 23 i=int(myInput) 24 nums.append(i) 25except: 26print'Error Number', 27 28 templist=list(nums) 29 nums.sort() 30 nums.reverse() 31print nums 32for i in range(0,len(templist),1): 33for j in range(i+1,len(templist),1): 34if str(templist[i])<str(templist[j]): 35 templist[i],templist[j]=templist[j],templist[i] 36print templist 37 38
6-6.
Strings. Create the equivalent to string.strip(): Take a string and remove all leading and trailing whitespace. (Use of string.*strip() defeats the purpose of this exercise.)
1#!/usr/bin/env python 2#-*- coding:utf-8 -*- 3#$Id: p0605.py 133 2010-04-25 11:16:34Z xylz $ 4 5''' 6This is a 'python' study plan for xylz. 7Copyright (C)2010 xylz (www.imxylz.info) 8''' 9 10def trim(s): 11''' 12 Take a string and remove all leading and trailing whitespace. 13''' 14if s is None:return None 15if len(s)==0:return'' 16 ret=[] 17for i in range(0,len(s),1): 18 c=s[i] 19if c !=''and c !='\t'and c!='\r'and c!='\n': 20 s=s[i:] 21break 22if i==len(s)-1:return'' 23for j in range(len(s)-1,-1,-1): 24 c=s[j] 25if c!=''and c!='\t'and c!='\r'and c!='\n': 26 s=s[:j+1] 27break 28if j==0:return'' 29return s 30 31 32if__name__=='__main__': 33''' 34 Create the equivalent to string.strip(): Take a string and remove all leading and trailing whitespace. (Use of string.*strip() defeats the purpose of this exercise.) 35''' 36for s in [" a book "," a book","a book",""," \r\n"]: 37 ns=trim(s) 38print"'%s' => '%s', len=%d"% (s,ns,len(ns)) 39