Download Built-in Function

Document related concepts
no text concepts found
Transcript
Introduction to Python
1
Materials based on contents from the course Programming with Python by Chad Haynes
Outline
•
•
•
•
•
•
Overview
Built-in objects
Functions and scopes
Object-oriented programming
Functional programming
Exercise
2
Python At First Glance
import math
Import a library module
def showArea(shape):
print "Area = %d" % shape.area()
Function definition
def widthOfSquare(area):
return math.sqrt(area)
class Rectangle(object):
def __init__(self, width, height):
self.width = width
self.height = height
Class definition
def area(self):
return self.width * self.height
###### Main Program ######
r = Rectangle(10, 20)
showArea(r)
Comment
Object instantiation
Calling a function
3
Why use Python?
•
•
•
•
•
•
•
Simple, clean syntax
Portable
Flexible
Large standard library
Short development time
Lots of 3rd-party tools/add-ons
Many good implementations
– CPython, PyPy, IronPython, Jython
• Strong support from open-source community
4
Similarities to Java
• Everything inherits from "object"
– Also numbers, functions, classes, …
– Everything is first-class
• Vast, powerful standard library
• Garbage collection
• Introspection, serialization, threads, net,…
5
Similarities to C++
• Multi-paradigm
– OOP, procedural, generic, functional (a little)
• Multiple inheritance
• Operator overloading
6
Python vs. Java/C++/C
• Typing: strong, but dynamic
– Names have no type
– Objects have types
• No declarations
• Sparse syntax
– No { } for blocks, just indentation
– No ( ) for if/while conditions
• Interactive interpreter
• # for comments
if (x < 10)
{
x = x + tmp;
y = y * x;
}
System.out.println(y);
Java
if x < 10:
x = x + tmp
y = y * x
print y
Python
7
Getting Started
• Python already included in most Linux
distributions
• Windows users can download from:
– http://python.org/download
– Add python to PATH to run scripts from
command line
8
Hello, World!
• C#
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, World");
}
}
• Python
print "Hello, World!"
9
Variables
>>> x = 23
>>> print x
23
>>> x = 'foo'
now it means 'foo'
>>> print x
foo
x becomes undefined >>> del x
>>> print x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
name x means 23
10
Variables
• Reference Model
– Variables refer to an object
– More than one variable can refer to the same
object
Var1
Var1_copy
Var2
11
Numeric Types
• Integers
– Generally 32 signed bits
• Long Integers
– Unlimited size
– Format: <number>L
– Example: 4294967296L
• Float
– Platform dependant “double” precision
• Complex
– Format: <real>+<imag>j
– Example: 6+3j
12
Strings
• A sequence of characters enclosed with quotes
• 3 quoting styles
– 'Single Quotes'
– "Double Quotes"
– """Triple Quotes"""
• Examples
>>> print 'This may contain a "'
This may contain a "
>>> print "A ' is allowed"
A ' is allowed
>>> print """Either " or ' are OK"""
Either " or ' are OK
13
Built-in Function: raw_input
• Syntax: raw_input([prompt])
– Use prompt to ask user to input a string
– Example
>>> info = raw_input('-> ')
-> Here is info
>>> print info
Here is info
14
Basic Operations
• Arithmetic
-
+
-
*
-
Example
//
/
**
%
abs
>>> 5 + 3
# Addition
8
>>> 2 ** 8
# Exponentiation
256
>>> 13 / 4
# Integer (Truncating) Division*
3
>>> float(13) / 4 # Float Division
3.25
>>> 13 % 4
# Remainder
1
>>> abs(-3.5)
# Absolute Value
3.5
* Becomes float division in version 3.x
15
Basic Operations
• Comparison
-
<
-
Results in 1 (true) or 0 (false)
-
Example
>>>
1
>>>
1
>>>
0
>>>
0
>>>
1
<=
>
>=
==
!=
<>
4 > 1.5
'this' != 'that'
4+3j == 4-2j
'5' == 5
0 < 10 < 20
16
Basic Operations
• Boolean
-
and
or
not
-
Based on Boolean Algebra
i1
i2
i1 and i2
i1 or i2
i1
not i1
1
1
1
1
1
0
1
0
0
1
0
1
0
1
0
1
0
0
0
0
17
Basic Operations
• Boolean
-
Example
>>>
0
>>>
1
>>>
0
>>>
1
1 == 1 and 2 >= 3
1 == 1 or 2 >= 3
not 5.3 != 2.2
# same as: not (5.3 != 2.2)
2 and '23' > '11' or 0
18
Strings - Operations
• Concatenation (+)
-
Syntax: string1 + string2
-
Example:
>>> 'Rockefeller' + 'University'
'RockefellerUniversity'
• Repetition (*)
-
Syntax: string * number
-
Example:
>>> 'dog' * 5
'dogdogdogdogdog'
19
Strings - Formatting
• C-Style formatting (extended printf)
-
Examples:
>>> "%i %s in the basket" % (2, "eggs")
'2 eggs in the basket'
>>> "%f to 2 decimal places: %.2f" %(2.0/9.0, 2.0/9.0)
'0.222222 to 2 decimal places: 0.22'
>>> length = 5
>>> obj = "fence"
>>> "Length of the %(obj)s is %(length)i" % vars()
'Length of the fence is 5'
20
Built-in Function: type
• Syntax: type(object)
-
Used to determine the type of an object
-
Example
>>> type(2.45)
<type 'float'>
>>> type('x')
<type 'str'>
>>> type(2**34)
<type 'long'>
>>> type(3+2j)
<type 'complex'>
21
Type Conversions
• Use built-in functions to convert between types
-
str()
-
Example
int()
float()
long()
complex()
bool()
>>> str(42.3)
'42.3'
>>> float('-1.32e-3')
-0.00132
>>> int('0243')
243
>>> int(2**34)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in ?
int(2**34)
OverflowError: long int too large to convert to int
>>> long(2**34)
17179869184L
22
Data Structures
• Lists
• Tuples
• Dicts
23
Lists
• Construction
-
Syntax: [elem1, elem2, …]
-
Heterogeneous, ordered sequence
-
Mutable
-
Example:
>>> list1 = [1, 'hello', 4+2j, 123.12]
>>> list1
[1, 'hello', (4+2j), 123.12]
>>> list1[0] = 'a'
>>> list1
['a', 'hello', (4+2j), 123.12]
24
Lists - Operations
• Concatenation (+)
-
Syntax: list1 + list2
-
Example:
>>> [1, 'a', 'b'] + [3, 4, 5]
[1, 'a', 'b', 3, 4, 5]
• Repetition (*)
-
Syntax: list * number
-
Example:
>>> [23, 'x'] * 4
[23, 'x', 23, 'x', 23, 'x', 23, 'x']
25
Indexing
• Indexing operator: [ ]
• Positive indices count from the left
• Negative indices count from the right
0
1
2
3
4
5
6
a
b
c
d
e
f
g
-7
-6
-5
-4
-3
-2
-1
sequence[0] == a
sequence[-7] == a
sequence[6] == g
sequence[-1] == g
sequence[2] == c
sequence[-5] == c
26
List Slicing
• Two indices separated by a colon
-
Available for both strings and lists
-
Example
>>> sequence = [0, 1, 2, 3, 4, 5, 6, 7]
>>> sequence[1:4]
[1, 2, 3]
>>> sequence[2:-1]
[2, 3, 4, 5, 6]
-
Missing Index implies end point
>>> sequence[:2]
[0, 1]
>>> sequence[3:]
[3, 4, 5, 6, 7]
27
Tuples
• Immutable version of list
-
Syntax: (elem1, elem2, …)
-
Items in tuple can not be altered
-
Example:
>>> tuple1 = (1, 5, 10)
>>> tuple1[2] = 2
Traceback (most recent call last):
File "<pyshell#136>", line 1, in ?
tuple1[2] = 2
TypeError: object doesn't support item assignment
28
Built-in Function: len
• Syntax: len(object)
-
Return the length of object
-
Example
>>> list1 = [1, 2, 3, 4, 5]
>>> len(list1)
5
>>> string1 = "length of a string"
>>> len(string1)
18
29
Dictionaries
• Mapping
-
Associate a key with a value
-
Each key must be unique
keys
'z'
'ab'
values
10
[2]
2.1
(3,8)
3
'hello'
30
Dictionaries
• Construction
-
Syntax: {key1: value1, key2: value2 …}
-
Unordered map
-
Example:
>>> dict1 = {'a': 1, 'b': 2}
>>> dict1
{'a': 1, 'b': 2}
>>> dict1['a']
1
>>> dict1['b']
2
31
Control Flow
Examples
if condition:
body
elif condition:
body
else:
body
if x%2 == 0:
y = y + x
else:
y = y - x
while condition:
body
while i < 0:
count = count + 1
for name in iterable:
body
for x in [1,2,3]:
sum = sum + x
32
Built-in Function: range
• Syntax: range([start,] stop[, step])
-
Generate a list of numbers from start to stop stepping every step
-
start defaults to 0, step defaults to 1
-
Example
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(1, 9)
[1, 2, 3, 4, 5, 6, 7, 8]
>>> range(2, 20, 5)
[2, 7, 12, 17]
33
Controlling Flow
• Using range with for
-
Generate list used by for with range
-
Example
>>> for i in range(4):
print i
0
1
2
3
34
Using Data Structures
• Data structures also have methods
• Use built-in function dir to list all available methods
• Example
>>> lst = [1, 3, 2]
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__repr__', '__rmul__', '__setattr__',
'__setitem__', '__setslice__', '__str__', 'append', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']
37
Lists - Methods
• append
-
Syntax: list.append(element)
-
Add element to end of list
-
Example:
>>> list1 = [3, '10', 2]
>>> list1.append('new')
>>> list1
[3, '10', 2, 'new']
40
Lists - Methods
• insert
-
Syntax: list.insert(index, element)
-
Insert element into list at position index
-
Example:
>>> list2 = [0, 1, 2, 3, 4, 5]
>>> list2.insert(3, 'new')
>>> list2
[0, 1, 2, 'new', 3, 4, 5]
42
Lists - Methods
• sort
-
Syntax: list.sort([cmpfunc])
-
Sort list in place
-
Example:
>>> list3 = [4, 12, 3, 9]
>>> list3.sort()
>>> list3
[3, 4, 9, 12]
44
Getting Help
• For interactive use, calling help function will invoke the
built-in help system
• Call help() without argument for interactive mode
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
|
str
|
basestring
|
object
|
| Methods defined here:
|
| __add__(...)
|
x.__add__(y) <==> x+y
|
| __contains__(...)
|
x.__contains__(y) <==> y in x
:
49
Functions and Scopes
50
Defining Functions
• Syntax: def func(arg1, …):
body
-
Body of function must be indented
-
If no value is returned explicitly, function will return None
-
Example:
>>> def average(num1, num2, num3):
sum = num1 + num2 + num3
avg = sum / 3.0
return avg
51
Functions
• Parameters
-
Parameters can be any type
-
A function can take any number of parameters (or none at all)
-
Example:
>>> def usage(programName, version):
print ‘%s Version %i' % (programName, version)
print 'Usage: %s arg1 arg2‘ % (programName)
>>> usage('Test', 1.0)
Test Version 1.0
Usage: Test arg1 arg2
52
Functions
• Default Parameters
-
One or more parameters can be given a default value
-
The function can be called with fewer arguments than there are
parameters
-
All non-default (required) parameters must precede default parameters
-
Example:
>>> def printName(last, first, mi=""):
print "%s, %s %s" % (last, first, mi)
>>> printName("Smith", "John")
Smith, John
>>> printName("Smith", "John", "Q")
Smith, John Q
53
Functions
• Calling functions
-
Syntax: func(arg1, arg2, … argn)
-
Order of arguments must match order of declared parameters
-
No type checking is done
-
Example
>>> def display(arg1, arg2, arg3):
print arg1
print arg2
print arg3
>>> display(1, 'x', 4.3)
1
x
4.3
54
Functions
• Keyword arguments
-
Functions can be called using the keyword of the argument
-
Syntax: func(keyword=value, …)
-
The order of the values passed by keyword does not matter
-
Example
def keywords(key1="X", key2="X", key3="X",key4="X"):
print key1, key2, key3, key4
>>> keywords(key3="O", key2="O")
X O O X
>>> keywords()
X X X X
55
Functions
• Functions as variables
-
Functions can be assigned
-
Example
def sub(a, b):
return a-b
>>> op = sub
>>> print op(3, 5)
-2
>>> type(op)
<type 'function'>
56
Functions
• Functions as parameters
-
Functions can be passed to other functions
-
Example
def convert(data, convertFunc):
for i in range(len(data)):
data[i] = convertFunc(data[i])
return data
>>> convert(['1', '5', '10', '53'], int)
[1, 5, 10, 53]
>>> convert(['1', '5', '10', '53'], float)
[1.0, 5.0, 10.0, 53.0]
>>> convert(['1', '5', '10', '53'], complex)
[(1+0j), (5+0j), (10+0j), (53+0j)]
57
Functions
• Returning multiple values
-
Return a tuple containing the values to return
-
Example
def separate(text, size=3):
start = text[:size]
end = text[-size:]
return (start, end)
>>> separate('sample text')
('sam', 'ext')
>>> start, end = separate('sample text')
>>> print start
sam
>>> print end
ext
58
Generators
• Generators are functions that generate
sequence of items
– Generated sequence can be infinite
def fibonacci():
i = j = 1
while True:
r, i, j = i, j, i+j
yield r
for rabbits in fibbonacci():
print rabbits
if rabbits > 100: break
1 1 2 3 5 8 13 21 34 55 89 144
59
Namespaces and Scopes
• Namespace
– A mapping from names to objects
– (Currently) implemented as Python dictionaries
• Scope
– A region of program where a namespace is directly
accessible
– Name references search at most 3 scopes: local,
global, built-in
– Assignments create or change local names by default
– Can force arguments to be global with global
command
60
Scope Example
x = 99
def func(Y):
Z = X+Y
return Z
func(1)
# X is not assigned, so it's global
61
Modules
• A file containing Python definitions and statements
-
Modules can be “imported”
-
Module file name must end in .py
-
Used to divide code between files
math.py
string.py
import math
import string
…
62
import Statement
• Syntax 1: import <module name>
-
Module name is the file name without the .py extension
-
You must use the module name to call the functions
-
Example
>>> import math
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2',
'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor',
'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf',
'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> print math.e
2.71828182846
>>> print math.sqrt(2.3)
1.51657508881
63
import Statement
• Syntax 2: from <module> import <name>
-
Import only a specific name from a module into global namespace
-
Module name is not required to access imported name
-
Example
>>> from math import sqrt
>>> sqrt(16)
4
>>> dir(math)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
64
import Statement
• Syntax 2a: from <module> import *
-
Import everything from a module into global namespace
-
Example
>>> dir()
['__builtins__', '__doc__', '__name__']
>>> from time import *
>>> dir()
['__builtins__', '__doc__', '__name__',
'accept2dyear',
'altzone', 'asctime',
'clock', 'ctime', 'daylight', 'gmtime',
'localtime', 'mktime', 'sleep', 'strftime',
'struct_time', 'time', 'timezone', 'tzname']
>>> time()
1054004638.75
65
Python Standard Libraries
• Some examples
sys - System-specific parameters and functions
time - Time access and conversions
thread - Multiple threads of control
re - Regular expression operations
email - Email and MIME handling package
httplib - HTTP protocol client
Tkinter - GUI package based on Tcl/Tk
• See http://docs.python.org/library/index.html
66
OO Programming
80
Defining a Class
• Syntax:
class name[(base)]:
body
• Creating a class with no superclass
class name:
body
Old-style class
class name(object):
body
New-style class
• Basically, classes are simply namespaces
class MyClass(object):
myvar = 30
>>> MyClass.myvar
30
81
Class Example
• All instance methods must explicitly take an
instance as the first parameter
– self is a commonly used name
class Rectangle(object):
def __init__(self, width, height):
self.width = width
self.height = height
Constructor
def area(self):
return self.width * self.height
>>> r = Rectangle(10, 20)
>>> Rectangle.area(r)
200
>>> r.area()
200
82
Inheritance
• Subclass must invoke parent's constructor
explicitly
class Square(Rectangle):
def __init__(self, width):
Rectangle.__init__(self, width, width)
>>> s = Square(100)
>>> s.area()
10000
83
Polymorphism
• All methods are virtual
import math
class Circle(object):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi*self.radius*self.radius
>>> shapes = [Square(5), Rectangle(2,8), Circle(3)]
>>> for x in shapes:
...
print x.area()
...
25
16
28.2743338823
84
Python Object Hooks
• Objects can support built-in operators by
implementing certain special methods
– The usual operators: +, -, *, /, **, &, ^, ~, !=
– Indexing (like sequences): obj[idx]
– Calling (like functions): obj(args,...)
– Iteration and containment tests
• for item in obj:...
• if item in obj:...
85
Functional Programming
86
Functional Approaches
• Taken from functional languages
-
Lisp/Scheme
-
Haskell
• Added to Python as built-in functions
-
map()
-
filter()
-
reduce()
-
zip()
87
Built-in function: map
• Perform an operation on each element of a list
-
A function is applied to each element
-
The results of each function call are used to generate a new list
-
The resulting list is always the same length as the original list
-
The original list is not altered
88
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
89
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
90
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
ŷ3
91
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
ŷ3
ŷ4
92
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
ŷ3
ŷ4
ŷ5
93
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
ŷ3
ŷ4
ŷ5
ŷ6
94
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
ŷ3
ŷ4
ŷ5
ŷ6
ŷ7
95
Built-in function: map
y1
y2
y3
y4
y5
y6
y7
y8
func
ŷ1
ŷ2
ŷ3
ŷ4
ŷ5
ŷ6
ŷ7
ŷ8
96
Built-in function: map
• Syntax 1: map(func, list)
-
Example: Convert a list of integers to strings
>>> lst1 = [1, 2, 3, 4]
>>> lst2 = map(str, lst1)
>>> print lst2
['1', '2', '3', '4']
-
The function (str) takes one argument
-
The result (lst2) is the same length as the original (lst1)
97
Built-in function: map
• What if the function requires more than one
argument?
-
Multiple lists can be passed to the map function
• Syntax 2: map(func, list1, …, listn)
-
All lists must be of same length
-
The function must take n parameters
98
Built-in function: map
• Example: adding numbers
def add2(a, b):
return a+b
>>> lst1 = [0, 1, 2, 3]
>>> lst2 = [4, 5, 6, 7]
>>> print map(add2, lst1, lst2)
[4, 6, 8, 10]
99
Code Comparison
lst1 = [1, 2, 3, 4]
lst2 = []
for element in lst1:
lst2.append(str(element))
lst1 = [1, 2, 3, 4]
lst2 = map(str, lst1)
100
Code Comparison
lst1 = [0, 1, 2, 3]
lst2 = [4, 5, 6, 7]
lst3 = []
for index in range(len(lst1)):
lst3.append(add2(lst1[index], lst2[index]))
lst1 = [0, 1, 2, 3]
lst2 = [4, 5, 6, 7]
lst2 = map(add2, lst1, lst2)
101
Benefits
• The map function can be used like an expression
-
Can be used as a parameter to a function
-
Example:
>>> lst1 = [1, 2, 3, 4]
>>> string.join(lst1)
# Error because lst1 contains ints
…
TypeError: sequence item 0: expected string, int found
>>> string.join( map(str, lst1) )
# Correct
'1 2 3 4'
102
Built-in function: filter
• Remove elements of a list based on a condition
-
Each element of a list is tested, those that fail are removed
-
The resulting list is the same length or shorter than the original
-
The original list is not altered
103
Built-in function: filter
• Syntax: filter(func, list)
-
Example: Remove all negative numbers
def removeNegative(number):
return number >= 0
>>> lst1 = [1, 2, -3, 4]
>>> lst2 = filter(removeNegative, lst1)
>>> print lst2
[1, 2, 4]
-
The function (str) takes one argument and returns 0 or 1
-
The result (lst2) is shorter than the original (lst1)
104
Code Comparison
lst1 = [1, 2, -3, 4]
lst2 = []
for element in lst1:
if removeNegative(element):
lst2.append(element)
lst1 = [1, 2, -3, 4]
lst2 = filter(removeNegative, lst1)
105
Built-in function: reduce
• Apply a function cumulatively to a sequence
-
The function must take 2 parameters
-
Function is applied to parameters from left to right
-
The list is reduced to a single value
-
The original list is not altered
106
Built-in function: reduce
y1
y2
y3
y4
func
t1
func
t2
func
t3
107
Example: Reduce by Adding
1
10
20
30
1+10
11
11+20
31
31+30
61
108
Built-in function: reduce
• Syntax 1: reduce(func, list)
-
Example: Find the sum of a list of integers
>>> lst1 = [1, 2, 3, 4]
>>> sum = reduce(operator.add, lst1)
>>> print sum
10
-
The function (operator.add) takes two arguments
-
The result is a single value
109
Built-in function: reduce
• Syntax 2: reduce(func, list, initialValue)
-
The initialValue is applied to func with the first value in the list
-
If the list is empty, the initialValue is returned
-
Example: Concatenating lists
>>> lst1 = [ [2, 4], [5, 9], [1, 7] ]
>>> result = reduce(operator.add, lst1, [100])
>>> print result
[100, 2, 4, 5, 9, 1, 7]
110
Code Comparison
lst1 = [1, 2, 3, 4]
sum = operator.add(lst1[0], lst1[1])
for element in lst1[2:]:
sum = operator.add(sum, element)
lst1 = [1, 2, 3, 4]
sum = reduce(operator.add, lst1)
111
Code Comparison
lst1 = [ [2, 4], [5, 9], [1, 7] ]
result = operator.add([100], lst1[0])
for element in lst1[1:]:
result = operator.add(sum, element)
lst1 = [ [2, 4], [5, 9], [1, 7] ]
result = reduce(operator.add, lst1, [100])
112
Built-in function: zip
• Combine multiple lists into one
-
Elements are paired by index
-
The resulting list is the same length as the shortest list supplied
-
Each element of resulting list contains a tuple
-
The original lists are not altered
113
Built-in function: zip
x1
x2
x3
x4
y1
y2
y3
y4
(x1, y1) (x2, y2) (x3, y3) (x4, y4)
114
Built-in function: zip
• Syntax: zip(list1, …, listn)
-
Example: Combine two lists
>>> lst1 = [1, 2, 3, 4]
>>> lst2 = ['a', 'b', 'c', 'd', 'e']
>>> result = zip(lst1, lst2)
>>> print result
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
-
The ‘e’ element was truncated since lst1 only has 4 elements
-
The result is a list of tuples
115
Code Comparison
lst1 = [1, 2, 3, 4]
lst2 = ['a', 'b', 'c', 'd', 'e']
lst3 = []
for index in range(min(len(lst1), len(lst2)):
lst3.append( (lst1[index], lst2[index]) )
lst1 = [1, 2, 3, 4]
lst2 = ['a', 'b', 'c', 'd', 'e']
lst3 = zip(lst1, lst2)
116
Uses for zip
• Iterate over two lists simultaneously
>>> produce = ['apples', 'oranges', 'pears']
>>> prices = [0.50, 0.45, 0.55]
>>> for fruit, cost in zip(produce, prices):
print '%s cost $%.2f'%(fruit, cost)
apples cost $0.50
oranges cost $0.45
pears cost $0.55
117
Uses for zip
• Create a dictionary using dict()
>>> produce = ['apples', 'oranges', 'pears']
>>> prices = [0.50, 0.45, 0.55]
>>> priceDict = dict(zip(produce, prices))
>>> print priceDict
{'pears': 0.55, 'apples': 0.5, 'oranges': 0.45}
118
List Comprehensions
• Generate new lists from old ones
-
Can simultaneously map and filter
-
More flexible than the built-in functions
119
Basic List Comprehensions
• Basic Syntax: [<exp> for <var> in <list>]
-
The resulting list is the result of exp evaluated for each var in list
-
Example: Increase each element by 1
>>> [x+1 for x in range(5)]
[1, 2, 3, 4, 5]
-
Example: Convert each element to a string
>>> [str(x) for x in range(5)]
['0', '1', '2', '3', '4']
120
More List Comprehensions
• Syntax: [<ex1> for <var> in <list> if <ex2>]
-
ex1 is only evaluated if ex2 is true
-
Example: Remove smallest element
>>> lst1 = [5, 10, 3, 9]
>>> [x for x in lst1 if x != min(lst1)]
[5, 10, 9]
-
Example: Sum all lists of size greater than 2
>>> lst1 = [[1, 2, 4], [3, 1], [5, 9, 10, 11]]
>>> [reduce(operator.add, x) for x in lst1 if len(x) > 2]
[7, 35]
121
More List Comprehensions
• Multiple for loops can be included
-
The loops will be nested
-
Example: Generate all possible combinations of letters a, c, g, t
>>> nucleo = ['a', 'g', 'c', 't']
>>> [a+b for a in nucleo for b in nucleo]
['aa', 'ag', 'ac', 'at', 'ga', 'gg', 'gc', 'gt', 'ca', 'cg',
'cc', 'ct', 'ta', 'tg', 'tc', 'tt']
122
Code Comparison
nucleo = ['a', 'g', 'c', 't']
results = []
for a in nucleo:
for b in nucleo:
results.append(a+b)
nucleo = ['a', 'g', 'c', 't']
results = [a+b for a in nucleo for b in nucleo]
123
Lambda Functions
• Anonymous functions
-
Body can consist of only a single expression
-
Execute slightly slower than normal functions
-
Can take any number of parameters
-
In general, lambda functions should be avoided
124
Lambda Functions
• Syntax : lambda p1[,…,pn]: <exp>
-
Expression should not use return
-
Example: adding two numbers
>>> add2 = lambda a,b: a+b
>>> print add2(1, 5)
6
-
Example: simple factorial
>>> fac = lambda x: reduce(lambda a,b: a*b, range(1, x+1))
>>> print fac(5)
120
125
References
• Python Documentation
 http://docs.python.org
• Python for Programmers by Alex Martelli
• Advanced Python (Understanding Python)
by Thomas Wouters
126
Exercise
• Write a Python program freq.py to:
– Fetch a text file from the web
– Then report the most 10 frequently used words
$ python freq.py http://www.cpe.ku.ac.th/~cpj/gpl.txt
345: the
221: of
192: to
184: a
151: or
128: you
102: license
98: and
97: work
91: that
$
127
Exercise – Hints
• Accessing command-line arguments
import sys
url = sys.argv[1]
• Reading a webpage
import urllib
contents = urllib.urlopen(url).read()
• Extracting all English words from text
import re
words = re.findall('[A-Za-z]+', text)
128