# lecture-11 by Awumsuri

VIEWS: 1 PAGES: 7

• pg 1
```									News                                            Recap from last time
• Programming Assignment #4 (Python) up         Interpreted, imperative, OO Language
and due next Monday night                     • Everything is an object
• Dynamic Typing

• Programming Assignment #5 (ML                 Programs are made up of:
interpreter) is up and is due two weeks       • Expressions
• Statements
after that                                      –   Assignment
–   if/elif/else
–   while-loops
–   Functions
• Classes (still to come)

Show recap code                                 Today: Revisit some objects
• Exploit features and build powerful
expressions

Base: int, float, complex

Sequence: string, tuple, list

What can sequences do ?                         Update subsequence s[i:j]=e
Select                                          Update subsequence: s[i:j] = e
• i-th element: s[i]
• subsequence (“slice”): s[i:j]                 • Changes the “object” referred to by s
• May change the length of the sequence
Update -- For mutable sequences (e.g. Lists)       – Increase: if RHS length > j-i
• Update i-th element: s[i] = e                    – Decrease: if RHS length < j-i
• Update subsequence: s[i:j] = e

1
Update subsequence s[i:j]=e                       What else can sequences do ?
>>> z = [1,2,3,4,5,6,7,8,9,10]
Q: Suppose you are given a sequence s
>>> z[3:6] = [“a”,“b”,“c”]
>>> z                                             How to find if the element x appears in s ?
[1,2,3,”a”,”b”,”c”,7,8,9,10]
>>> z[3:6] = [“a”, “b”] * 2                                             x in s
>>> z
[1,2,3,”a”,”b”,”a”,”b”,7,8,9,10]
Works for any sequence type …
>>> z[4:]=[]
>>> z
[1,2,3,”a”]
>>> z[:0] = [“al”, “be”]
>>> z
[“al”,”be”,1,2,3,”a”,”b”,”a”,”b”,7,8,9,10]

Sequence “contains”                 x in s        What can sequences do ?
>>> “a” in “cat”                               Select
True                                           • i-th element: s[i]
>>> “a” in “entebbe”                           • subsequence (“slice”): s[i:j]
Update -- For mutable sequences (e.g. Lists)
False
• Update i-th element: s[i] = e
>>> “a” in (“c”, “a”, “t”)                     • Update subsequence: s[i:j] = e
True                                           Member
>>> 2 in [1,2,3,4,5]                           • Is an element in a sequence: x in s

True
>>> 2 in [1,4,“92”,2.4]
False

Doesn’t Python have For-Loops ?                   Iteration                        for x in s:
Why haven’t we seen For-loops yet ?                >>> for x in [“Sorin”, “ain’t”, “cool”]:
print x,len(x)
• Because they are connected to sequences
Sorin 5
For-loops are used to iterate over sequences
ain’t 5
• Unlike in C/Java/…                               cool 4
• Elegant, powerful mechanism – use it!            Works for any sequence …
x=s[0]           >>> for c in “chimichanga”:
<BODY>
print c*3
x=s[1]
for x in s:                       <BODY>
ccc
...              hhh
<BODY>                          x=s[len(s)-1]    iii
<BODY>           mmm …

2
Iteration                     for x in s:                Iteration + binding               for x,… in s:
>>> s=0                                                 If s is a sequence of tuples/sequences, then we can
>>> z=(1,2,3,4.0,”5”)      #tuple                       Bind to individual elements of “subsequences”
>>> for i in z:                                          >>>craigslist = [("alien",3.50),
s = s + i                                          ("dinosaur",1.90), ("quiz",100.50),
ERROR
130","priceless")]
>>> s
>>>for i,p in craislist:
10
print “One”,i,“costs”,p
>>> s=0                      One alien costs 3.5
Can’t add string to float       >>> for i in z:           One dinosaur costs 1.9
• Note that first 4 elts added!        s=s+float(i)       One quiz costs 100.5
• Dynamic Types!                >>> s                     One quesadilla costs 3.0
• Run-time Type Error           15                        One good grade in 130 costs priceless

Old school For-loops                                     But lookout!
for(i=0,i<10,i++){       For-loops are used to iterate over sequences
There’s a simple way to write
print i;
good-old for-loops              }                                      for x in s:
Built-in function: range
<BODY>
>>> range(10)
[0,1,2,3,4,5,6,7,8,9]
>> for i in range(10):                                  What if object referred to by s is changed in BODY?
print i

>>> range(5,15)       #fixed upper bound
Unpleasantness ensues:
[5,6,7,8,9,10,11,12,13,14]                              • Try to ensure this never happens
>>> range(15,5,-1)    #step                             • Iterate over a “copy” of the object
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6]                       – s[:]

But lookout!                                             But lookout!
def funny_fun(s):           def dup_by_k(s,k):           def funny_fun(s):              def dup_by_k(s,k):
for x in s:                 for x in s:                  for x in s:                    for x in s[:] :
print x                     print x                      print x                        print x
s[len(s):] = [x]            s = s + x*k                  s[len(s):] = [x]               s = s + x*k
return s                                                    return s
Creates new object w/                                       Creates new object w/
being iterated over!                                     being iterated over!
• Loops forever                                          • Loops forever

Iteration object is what s      To make it more             Iteration object is what s
“originally” referred to,       readable                    “originally” referred to,
which is unchanged                                          which is unchanged

3
What can sequences do ?                                 What else ?
Select                                                  Three useful functions for lists from ML ?
• i-th element: s[i]                                    • map
• subsequence (“slice”): s[i:j]                         • filter
Update -- For mutable sequences (e.g. Lists)            • fold (a.k.a. reduce)
• Update i-th element: s[i] = e                         Built-in in Python:
• Update subsequence: s[i:j] = e
Member: x in s
Iteration: for x in s: <body>

map                                                     filter
def dup(x):
• Works for all sequences, returns same kind of sequence
return 2*x

>>> z = range(10)                                       >>> def even(x): return int(x)%2==0
>>> z                                                   >>> filter(even,range(10))
[0,1,2,3,4,5,6,7,8,9]                                   [0,2,4,6,8]
>>> map(dup,z)                                          >>> filter(even,”1234096001234125”)
[0,2,4,6,8,10,12,14,16,18]                              “240600242”
>>>map(dup,”chimichanga”)                               >>> filter(even,(1,2.0,3.2,4))
[“cc”,”hh”,”ii”,”mm”,”ii”,”cc”,”hh”,”                   (2,4)
aa”,”nn”,”gg”,”aa]
• Again, note the polymorphism that we get from
• Works for all sequences, returns a list              dynamic types and conversion
• More flexible ways to call it, see documentation

reduce                                                  What can sequences do ?
• i.e. fold                                             Select
>>> def add(x,y): x+y                             • i-th element: s[i]
>>> reduce(add,range(10),0)                       • subsequence (“slice”): s[i:j]
45                                                Update -- For mutable sequences (e.g. Lists)
>>> def fac(x):                                   • Update i-th element: s[i] = e
def mul(x,y): return x*y                     • Update subsequence: s[i:j] = e
return reduce(prod,range(1, x+1),1)          Member: x in s
>>> fac(5)
Iteration: for x in s: <body>
120
map,filter,reduce

4
List Comprehensions                                List Comprehensions
A cleaner, nicer way to do map-like operations

>>> [ x*x for x in range(10)]                  Syntax:   >>> [ex for x in s]
[0,1,4,9,16,25,36,49,64,81]
>>> [2*x for x in “yogurt cheese”]           Equivalent to:
[“yy”,”oo”,”gg”,”uu”,”rr”,”tt”,…]

List Comprehensions                                List Comprehensions

A cleaner, nicer way to do map+filter-like operations

Syntax:                                               >>> [ x*x for x in range(10) if even(x)]
>>> [ex for x in s]
[0,4,16,36,64]
Equivalent to: >>> def function(x): return ex           >>> [ 2*x for x in “0123456” if even(x)]
>>> map(function, s)                   [“00”,“22”,“44”,“66”]
>>> [z[0] for z in craislist z[1]<3.0]
[“dinosaur”]

List Comprehensions                                List Comprehensions

Syntax: >>> [ex for x in s if cx ]                 Syntax: >>> [ex for x in s if cx ]

Equivalent to:                                     Equivalent to:

>>> def map_fn(x): return ex
>>> def filter_fn(x): return cx
>>> map(map_fn, filter(filter_fn, s))

5
List Comprehensions                                      What can sequences do ?
Select
Can “nest” the for to iterate over multiple sequences    • i-th element: s[i]
• subsequence (“slice”): s[i:j]
>>>[(x,y) for x in range(3) for y range(3)]
Update -- For mutable sequences (e.g. Lists)
[(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,
1),(2,2)]                                               • Update i-th element: s[i] = e
>>>[(x,y) for x in range(3) for y in range(3)             • Update subsequence: s[i:j] = e
if x > y]                                               Member: x in s
[(1,0),(2,0),(2,1)]                                       Iteration: for x in s: <body>
map,filter,reduce
Comprehensions: [ex for x in s if cx]

Quicksort in Python                                      Today: Revisit some objects
def sort(L):                                             • Exploit features and build powerful
if L==[]: return L                                       expressions
else:
l=sort([x for x in L[1:] if x < L[0]])                     Base: int, float, complex
r=sort([x for x in L[1:] if x >= L[0]])
return(l+L[0:1]+r)
Sequence: string, tuple, list

Maps (Dictionary): key → value

Key data structure: Dictionaries                         Using Dictionaries
Associative arrays, Hash tables …                        Unsorted list of key,value pairs

Empty Dictionary: {}
A table storing a set of “keys”,
And a “value” for each key.                              Non-empty Dictionary: {k1:v1,k2:v2,…}

Any (immutable) object can be a key!                     Membership: is k in dict: k in d
• int,float,string,tuples…                               Lookup value of key: d[k]

Very useful!                                             Set value of key: d[k]=v

6
Dictionaries                                        Dictionaries
>>> d={}                                              def freq(s):              def plotfreq(s):
d={}                      d=freq(s)
for c in s:               for k in d.keys():
>>> d[“ceviche”] = 3.95                                   if c in d: d[c]+=1          print k, “*”*d[k]
>>> d                                                     else: d[c]=1
{…}                                                     return d
>>> d[“burrito”]                                    >>>   d=plotfreq([1,1,3.0,”A”,3.0,”A”,”A”,1,2,3.0,1,”A”])
3.50                                                >>>   d
>>> d.keys()                                        …
…                                                   >>>   d = plotfreq(“avrakedavra”)
>>>   d.keys()
>>> d.values()
>>>   d
…

…
<BODY>

>>> f.close

You now know enough to do PA5
• Python Tutorial: How to open files, read lines
• Use the help command
• Document every function: What does it do ?

7

```
To top