Python

CS314

In [65]:
z = [1,2,3,4,5,6,7,8,9,10]
In [66]:
z[3:6] = ["a","b","c"]
In [67]:
z
Out[67]:
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9, 10]
In [68]:
z[3:6] = ["a", "b"] * 2
In [69]:
z
Out[69]:
[1, 2, 3, 'a', 'b', 'a', 'b', 7, 8, 9, 10]
In [70]:
z[4:]=[]
In [71]:
z
Out[71]:
[1, 2, 3, 'a']
In [72]:
z[:0] = ["al", "be"]
In [73]:
z
Out[73]:
['al', 'be', 1, 2, 3, 'a']
In [74]:
"a" in "cat"
Out[74]:
True
In [75]:
"a" in "entebbe" 
Out[75]:
False
In [76]:
"a" in ("c", "a", "t")
Out[76]:
True
In [77]:
2 in [1,2,3,4,5]
Out[77]:
True
In [78]:
2 in [1,4,"92",2.4]
Out[78]:
False
In [79]:
for x in ["Midterms", "ain’t", "cool"]: 
    print (x,len(x))
Midterms 8
ain’t 5
cool 4
In [80]:
for c in "chimichanga": 
    print (c*3)
ccc
hhh
iii
mmm
iii
ccc
hhh
aaa
nnn
ggg
aaa

Quiz

What is the value of s after executing the following program?

  • A 1
  • B 6
  • C 10.0
  • D Error
In [81]:
s = 0
z = (1,2,3,4.0,"5") #tuple
for i in z:
    s = s+i
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-81-7757bc3fb8e0> in <module>
      2 z = (1,2,3,4.0,"5") #tuple
      3 for i in z:
----> 4     s = s+i

TypeError: unsupported operand type(s) for +: 'float' and 'str'
In [82]:
s
Out[82]:
10.0
s = 0
z = (1,2,3,4.0,"5") #tuple
for i in z:
    s = s+i
  • Note that first 4 elements added!
  • Dynamic Types!
  • Run-time Type Error
In [83]:
s = 0
z = (1,2,3,4.0,"5") #tuple
for i in z:
    s = s+float(i)
In [84]:
s
Out[84]:
15.0

Itetration + binding

If s is a sequence of tuples/sequences, then we can Bind to individual elements of "subsequences".

In [85]:
craigslist = [("alien",3.50), ("dinosaur",1.90),\
              ("quiz",100.50), ("quesadilla",3.00),\
              ("good grade in 314","priceless")]
In [86]:
for i,p in craigslist:
    print ("One", i, "costs", p)
One alien costs 3.5
One dinosaur costs 1.9
One quiz costs 100.5
One quesadilla costs 3.0
One good grade in 314 costs priceless

Old school For-loops

  • There’s a simple way to write good-old for-loops.
for(i=0,i<10,i++){ 
    print i;
}
  • Built-in function: range
In [87]:
list(range(10))
Out[87]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [88]:
list(range(5,15)) #fixed upper bound
Out[88]:
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
In [90]:
list(range(15,5,-1)) #step

for x in range(10):
    print (x)
0
1
2
3
4
5
6
7
8
9
def funny_fun(s):
    for x in s:
        print x 
        s[len(s):] = [x]
  • Add x to end object
  • being iterated over!
    • Loop forever
In [91]:
def dup_by_k(s,k):
    for x in s:
        print (x)
        s = s + x*k 
    return s

dup_by_k("1234", 5)
1
2
3
4
Out[91]:
'123411111222223333344444'
  • Creates new object w/ x*k added at end
  • Iteration object is what s "originally" referred to, which is unchanged
In [92]:
def dup_by_k(s,k):
    for x in s[:]:
        print (x)
        s = s + x*k 
    return s

dup_by_k("1234", 5)
1
2
3
4
Out[92]:
'123411111222223333344444'

Map

In [93]:
def dup(x):
    return 2 * x
In [94]:
z = range(10)
In [95]:
list(z)
Out[95]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [96]:
z = map(dup,z)
In [97]:
list(z)
Out[97]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [98]:
z = map(dup,"chimichanga")
In [99]:
list(z)
Out[99]:
['cc', 'hh', 'ii', 'mm', 'ii', 'cc', 'hh', 'aa', 'nn', 'gg', 'aa']
  • Works for all sequences, returns a list

Filter

  • Works for all sequences, returns same kind of sequence
In [100]:
def even(x): 
    return int(x)%2==0
In [101]:
result = filter(even,range(20))

print(list(result))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [102]:
result = filter(even,"1234096001234125")

print(list(result))
['2', '4', '0', '6', '0', '0', '2', '4', '2']
In [103]:
result = filter(even,(1,2.0,3.2,4))

print(list(result))
[2.0, 4]
  • Again, note the polymorphism that we get from dynamic types and conversion

Reduce

  • i.e. fold
In [104]:
from functools import reduce

def add(x,y): # x is accumulator and y is list element
    return x+y
In [105]:
l = range(10)
print ("l = ", l)

reduce(add, l, 0)
l =  range(0, 10)
Out[105]:
45
In [106]:
def fac(x):
    def mul(x,y): # x is accumulator and y is list element
        return x*y
    
    l = list(range(1, x+1))
    print ("l = ", l)
    
    return reduce(mul, l, 1)
In [107]:
fac(5)
l =  [1, 2, 3, 4, 5]
Out[107]:
120

List Comprehension

  • A cleaner, nicer way to do map-like operations
In [108]:
[ x*x for x in range(10)]
Out[108]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [109]:
[2*x for x in "yogurt cheese"]
Out[109]:
['yy', 'oo', 'gg', 'uu', 'rr', 'tt', '  ', 'cc', 'hh', 'ee', 'ee', 'ss', 'ee']

List Comprehension

  • A cleaner, nicer way to do map+filter-like operations
In [110]:
[ x*x for x in range(10) if even(x)]
Out[110]:
[0, 4, 16, 36, 64]
In [111]:
[ 2*x for x in "0123456" if even(x)]
Out[111]:
['00', '22', '44', '66']
In [112]:
craigslist
Out[112]:
[('alien', 3.5),
 ('dinosaur', 1.9),
 ('quiz', 100.5),
 ('quesadilla', 3.0),
 ('good grade in 314', 'priceless')]
In [113]:
[z[0] for z in craigslist if type(z[1])==float and z[1]<3.0]
Out[113]:
['dinosaur']

List Comprehension

  • Can “nest” the for to iterate over multiple sequences
In [114]:
[(x,y) for x in range(3) for y in range(3)]
Out[114]:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
In [115]:
[(x,y) for x in range(3) for y in range(3) if x > y]
Out[115]:
[(1, 0), (2, 0), (2, 1)]
In [116]:
def sort(L):
    if L==[]: 
        return L 
    else:
        l=sort([x for x in L[1:] if x < L[0]]) 
        r=sort([x for x in L[1:] if x >= L[0]]) 
        return(l+L[0:1]+r)
    
sort([5,3,1,4,2])
Out[116]:
[1, 2, 3, 4, 5]
In [117]:
d = {}
d["ceviche"] = 3.95
d["burrito"] = 3.50
In [118]:
d
Out[118]:
{'ceviche': 3.95, 'burrito': 3.5}
In [119]:
d["burrito"]
Out[119]:
3.5
In [120]:
d.keys()
Out[120]:
dict_keys(['ceviche', 'burrito'])
In [121]:
d.values()
Out[121]:
dict_values([3.95, 3.5])
In [122]:
def freq(s): 
    d={}
    for c in s:
        if c in d: 
            d[c]+=1 
        else: 
            d[c]=1
    return d
In [123]:
def plotfreq(s): 
    d=freq(s)
    for k in d.keys(): 
        print (k, "*"*d[k])
    return d
In [124]:
d=plotfreq([1, 1, 3.0, "A", 3.0, "A", "A", 1, 2, 3.0, 1, "A"])
1 ****
3.0 ***
A ****
2 *
In [125]:
d
Out[125]:
{1: 4, 3.0: 3, 'A': 4, 2: 1}
In [126]:
d = plotfreq("avrakedavra")
a ****
v **
r **
k *
e *
d *
In [127]:
d
Out[127]:
{'a': 4, 'v': 2, 'r': 2, 'k': 1, 'e': 1, 'd': 1}