Advanced Python topics
Advanced Python topics
Advanced Python topics
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Lecture 21: More <strong>Advanced</strong> <strong>Python</strong><br />
The set data type<br />
Command line arguments<br />
Redirection and pipe<br />
More on file operations<br />
More on string formatting<br />
More built-in functions: zip(), xrange()<br />
List comprehensions<br />
lambda functions<br />
Exceptions
COMP 116: Introduction to Scientific Programming<br />
The set Data Type<br />
‣ Set - unordered collections of unique elements.<br />
‣ Create a set<br />
• set(‘abcde’)<br />
• set([‘hello’, ‘world’, ‘my’, ‘friends’])<br />
‣ Operations on a set<br />
• len(s): cardinality of set s<br />
• x in s: test x for membership in s<br />
• x not in s: test x for non-membership in s<br />
© 2013 Yinqian Zhang 2
COMP 116: Introduction to Scientific Programming<br />
Set Operations<br />
‣ Operations on a set (Con’t)<br />
• s.issubset(t): test whether every element in s is in t<br />
• s.issuperset(t): test whether every element in t is in s<br />
• s.union(t): new set with elements from both s and t<br />
• s.intersection(t): new set with elements common to s<br />
and t<br />
• s.difference(t): new set with elements in s but not in t<br />
• s.symmetric_difference(t): new set with elements in<br />
either s or t but not both<br />
© 2013 Yinqian Zhang 3
COMP 116: Introduction to Scientific Programming<br />
Manipulate Elements in A Set<br />
‣ Operations on a set<br />
• s.update(t): return set s with elements added from t<br />
• s.add(x): add element x to set s<br />
• s.remove(x): remove x from set (error if not present)<br />
• s.discard(x): removes x from set s if present<br />
• s.pop(): remove and return an arbitrary element from s;<br />
(error if not present)<br />
• s.clear(): remove all elements from set s<br />
© 2013 Yinqian Zhang 4
COMP 116: Introduction to Scientific Programming<br />
Compare Two Sets<br />
‣ s == t<br />
• if and only if every element of each set is contained in<br />
the other (each is a subset of the other).<br />
‣ s > t<br />
• if and only if t is a proper subset of s (is a subset, but is<br />
not equal).<br />
‣ Two arbitrary sets may not have >, < or ==<br />
relationship.<br />
© 2013 Yinqian Zhang 5
COMP 116: Introduction to Scientific Programming<br />
Command Line Arguments<br />
‣ Run a <strong>Python</strong> program with arguments<br />
• python example.py arg1 arg2 arg3<br />
‣ How to access to the command line arguments<br />
from within the <strong>Python</strong> program?<br />
• import sys<br />
for item in sys.argv:<br />
print item<br />
© 2013 Yinqian Zhang 6
COMP 116: Introduction to Scientific Programming<br />
Exercises: Command Line Arguments<br />
‣ Write a program which accept two integers from<br />
the command line and print on the terminal the sum<br />
of the two integers.<br />
© 2013 Yinqian Zhang 7
COMP 116: Introduction to Scientific Programming<br />
I/O Redirection<br />
‣ I/O redirection: redirecting the standard output (or<br />
standard input) to (or from) a file.<br />
‣ Example:<br />
• In the <strong>Python</strong> file test.py:<br />
<br />
print 'this is a test'<br />
• The following command redirects the output to a file<br />
<br />
python test.py > a.txt<br />
• The following command redirects and appends the<br />
output to a file<br />
<br />
python test.py >> a.txt<br />
© 2013 Yinqian Zhang 8
COMP 116: Introduction to Scientific Programming<br />
I/O Redirection (Con’t)<br />
‣ Redirection standard input from a file<br />
• In the <strong>Python</strong> file test.py:<br />
<br />
a = raw_input()<br />
b = raw_input()<br />
print int(a) + int(b)<br />
• The content of file a.txt:<br />
1<br />
2<br />
• The following command redirects the input from a file<br />
<br />
python test.py < a.txt<br />
© 2013 Yinqian Zhang 9
COMP 116: Introduction to Scientific Programming<br />
Pipe<br />
‣ A pipe joins the standard output stream from one<br />
process to the standard input stream of another<br />
process in the following manner:<br />
‣ Example:<br />
• command1 | command2<br />
© 2013 Yinqian Zhang 10
COMP 116: Introduction to Scientific Programming<br />
Pipe (Con’t)<br />
‣ Exercises: using pipe to connect two python<br />
programs.<br />
• python test1.py | python test2.py<br />
# test1.py<br />
import random<br />
print random.randint(1, 10)<br />
print random.randint(1, 10)<br />
# test2.py<br />
a = raw_input()<br />
b = raw_input()<br />
print '%d + %d = %d' % (int(a), int(b), int(a) + int(b))<br />
© 2013 Yinqian Zhang 11
COMP 116: Introduction to Scientific Programming<br />
More on File Operations: tell()<br />
‣ The tell() method returns the current position<br />
within the file.<br />
• the next read or write will occur at that many bytes from<br />
the beginning of the file<br />
with open('a.txt', 'r') as f:<br />
while True:<br />
print f.tell()<br />
line = f.readline()<br />
if not line:<br />
break<br />
© 2013 Yinqian Zhang 12
COMP 116: Introduction to Scientific Programming<br />
More on File Operations: seek()<br />
‣ The seek(offset[, from]) method changes the<br />
current file position.<br />
• offset: the number of bytes to be moved.<br />
• from: the reference position from where the bytes are to<br />
be moved.<br />
<br />
<br />
<br />
from = 0, the beginning of the file as the reference position<br />
from = 1, the current position as the reference position<br />
from = 2, the end of the file as the reference position.<br />
© 2013 Yinqian Zhang 13
COMP 116: Introduction to Scientific Programming<br />
More on File Operations: seek()<br />
‣ Example of seek():<br />
• Omit the first 10 characters of a file<br />
with open('a.txt', 'r') as f:<br />
f.seek(10, 0)<br />
print f.read()<br />
• Read the only the last character of a file<br />
with open('a.txt', 'r') as f:<br />
f.seek(-1, 2)<br />
print f.read()<br />
© 2013 Yinqian Zhang 14
COMP 116: Introduction to Scientific Programming<br />
More on String Formatting<br />
‣ x = 3.0; print '%f' % (1/x)<br />
• 0.333333<br />
‣ %[flags][width][.precision]code<br />
• code: d, f, …<br />
• flags:<br />
<br />
<br />
<br />
-: left justification<br />
+: numeric sign<br />
0: zero fills<br />
• width: total width of the formatted string<br />
• precision: number of digits after the decimal point<br />
‣ x = 3.0; print '%-15.4f' % (1/x)<br />
© 2013 Yinqian Zhang 15
COMP 116: Introduction to Scientific Programming<br />
More Built-in Functions: zip()<br />
‣ zip(): access multiple sequences in parallel<br />
L1 = [1, 2, 3, 4]<br />
L2 = [5, 6, 7, 8]<br />
L3 = [9, 10, 11, 12]<br />
for i in zip(L1, L2, L3):<br />
print i<br />
#output<br />
#(1, 5, 9)<br />
#(2, 6, 10)<br />
#(3, 7, 11)<br />
#(4, 8, 12)<br />
© 2013 Yinqian Zhang 16
COMP 116: Introduction to Scientific Programming<br />
More Built-in Functions: zip()<br />
‣ Construct a dictionary with zip()<br />
Keys = ['a', 'b', 'c']<br />
Values = [1, 2, 3]<br />
D = dict(zip(Keys, Values))<br />
print D<br />
# output<br />
# {'a': 1, 'c': 3, 'b': 2}<br />
© 2013 Yinqian Zhang 17
COMP 116: Introduction to Scientific Programming<br />
More Built-in Functions: xrange()<br />
‣ xrange()<br />
• xrange() is similar to range(), but returns an xrange<br />
object instead of a list.<br />
• xrange() yields the same values as the corresponding<br />
list, without actually storing them all simultaneously.<br />
for i in xrange(100000):<br />
print i<br />
© 2013 Yinqian Zhang 18
COMP 116: Introduction to Scientific Programming<br />
List Comprehensions<br />
‣ The basic format<br />
• L = [x + 3 for x in range(10)]<br />
• equals:<br />
L = []<br />
for i in range(10):<br />
L.append(i+3)<br />
‣ Complicated formats<br />
• L = [x + y for x in range(10) for y in range(100, 200)]<br />
• L = [x for x in range(10) if x % 3 == 1]<br />
© 2013 Yinqian Zhang 19
COMP 116: Introduction to Scientific Programming<br />
List Comprehensions (Con’t)<br />
‣ Using list comprehensions on files<br />
• Strip the new line characters of each line<br />
lines = [line.rstrip('\n') for line in open('a.txt', 'r')]<br />
print lines<br />
• Read lines start with certain requirements<br />
lines = [line.rstrip('\n') for line in open('a.txt', 'r') if<br />
line[0].isdigit()]<br />
print lines<br />
© 2013 Yinqian Zhang 20
COMP 116: Introduction to Scientific Programming<br />
The lambda Functions<br />
‣ lambda functions: anonymous functions<br />
• lambda: arg1, arg2, arg3,..argN: expressions<br />
‣ A lambda function is an expression, not a<br />
statement.<br />
• appear in a list, or assigned to a variable<br />
‣ A lambda function’s body is a single expression,<br />
not a block of statements.<br />
• as simple as the return statement of def<br />
• limited logic without if, while statements<br />
© 2013 Yinqian Zhang 21
COMP 116: Introduction to Scientific Programming<br />
The lambda Functions<br />
‣ Example: a simple function<br />
f = lambda x: x**2<br />
print f(2)<br />
‣ Example: max_of_two()<br />
max_of_two = lambda x, y: x if x > y else y<br />
print max_of_two(2, 3)<br />
‣ Example: Sort a dictionary by value:<br />
D = {'a':2, 'b':1, 'c':3}<br />
print sorted(D.items(), key=lambda x: x[1])<br />
© 2013 Yinqian Zhang 22
COMP 116: Introduction to Scientific Programming<br />
Exceptions<br />
‣ <strong>Python</strong> raises exceptions whenever it detects errors<br />
in programs at runtime.<br />
• The exception will be handled by the default exception<br />
handler, which stops the program and prints an error<br />
message.<br />
‣ In order to deal with the errors in your <strong>Python</strong><br />
program, rather than having the program<br />
terminated, you need to deal with the exceptions.<br />
© 2013 Yinqian Zhang 23
COMP 116: Introduction to Scientific Programming<br />
The try Statements<br />
‣ The try statement is a compound statement.<br />
‣ Basic form:<br />
try:<br />
<br />
except :<br />
<br />
except (, ):<br />
<br />
except:<br />
# all other types of exceptions<br />
<br />
else:<br />
# optional<br />
# if no exception occurs<br />
© 2013 Yinqian Zhang 24
COMP 116: Introduction to Scientific Programming<br />
The try Statements<br />
import os<br />
try:<br />
os.mkdir('folder')<br />
except WindowsError:<br />
print 'folder already exists'<br />
with open('folder/a.txt', 'w+') as f:<br />
print f.read()<br />
© 2013 Yinqian Zhang 25