Emil Sekerinski, McMaster University, Winter Term 16/17 ...cs1md3/07 Structured Data Types.pdf ·...
Transcript of Emil Sekerinski, McMaster University, Winter Term 16/17 ...cs1md3/07 Structured Data Types.pdf ·...
EmilSekerinski,McMasterUniversity,WinterTerm16/17COMPSCI1MD3IntroductiontoProgramming
Liketuples,listsareorderedcollections.Elementsdon'thavetobeofthesametype.Elementscanoccurmultipletimes
Operation Notation
emptylist,listwithE,listwithE,F,… [],[E],[E, F],[E, F, G],…
listLindexedatI L[I]
suffixofLstartingatI L[I:]
prefixofLuptoI L[:I]
sliceofLstartingatIuptoJ L[I:J]
listLconcatenatedwithM L+M
lengthofL len(L)
EmemberofL,notmemberofL E in L,E not in L
LrepeatedItimes L*I,I*L
occurrencesofEinL L.count(E)
firstindexofEinL L.index(E)
Unliketuplesandstrings,listsaremutable>>> a = [1, 2, 3]; a[1] = 4; a>>> a = [1, 2, 3]; a[1:] = [5, 6]; a
Anumberoffunctionsupdatelistsinsitu Operation Notation
appendelementEtolistL L.append(E)
extendlistLwithlistM L.extend(M)
insertEatindexI L.insert(I, E)
deleteelementatindexI L.remove(I)
returnelementatindexIanddeleteit L.pop(I)
reverselistL L.reverse()
However,mutabilitymayleadtoaliasing,whichcanbeasourceoferrors>>> a = [1, 2, 3]; b = a; a; b>>> a = a + [4]; a; b
>>> a = [1, 2, 3]; b = a; a; b>>> a[1] = 5; a; b
a
b [1,2,3]
b
a
[1,2,3]
[1,2,3,4]
a
[1,2,3]b
a
[1,5,3]b
>>> a = [1, 2, 3]; b = [7, a, 9]; a; b>>> a.append(4); a; b
a [1,2,3]
b [7, ,9]
a [1,2,3,4]
b [7, ,9]
a = [1, 2, 3]
b = a
c = [4, 5, b]
a[0] = c[1]
d = c[2]
e = d[0]
a
[1,2,3]
a
b [1,2,3]
a
b [1,2,3][4,5, ]
c
a
b [5,2,3][4,5, ]
c
e == 5
a
b [5,2,3][4,5, ]
cd
Setcomprehensioninmathematics:{2i|i∈[0,10)}={1,2,4,8,16,32,64,128,256,512}
InPython,thegeneralformoflistcomprehensionis
[E for X in F if B]withvariableX,expressionsE,F,andBooleanexpressionB.Similartoforloops,Xtakesvaluesinthespecifiedorder>>> [2**i for i in range(10)]>>> [i for i in range(20) if i%2 == 0]>>> [i%10 for i in range(20)]>>> [i%3 == 0 for i in range(20)]
Allcandidateprimenumbersarewrittendown,startingfrom2,sayuptobutnotincludingn=20:2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19Allmultiplesof2areremoved,asthesearenotprimes:2 3 5 7 9 11 13 15 17 19Thenextunvisitednumberis3.Allmultiplesof3areremoved:2 3 5 7 11 13 17 19Thisprocesscontinueswithunvisitednumbers.Akeyobservationiswhenthiscanstop:thereisnopointinremovingmultiplesof5withfactorslessthan5,like2*5,3*5asthesehavebeeneliminatedalready;thereisnopointinremovingmultiplesof5withfactorsof5orgreater,asthesearegreaterthan20:onlymultipliesoffactorsupto√nneedtobeeliminated!
SifttheTwosandsifttheThrees,TheSieveofEratosthenes.Whenthemultiplessublime,ThenumbersthatremainarePrime.EratosthenesofCyrene,Greekmathematician,circa200bc
WeuseaBooleanlistoflengthntokeepprospectiveprimes.Whenmultiplesofiareeliminated,thefirstonetobeconsideredisi*i,asthoselesshavealreadybeeneliminated.Inrange(a, b, c),parametercspecifiesthestep:def eratosthenes1(n): a = n*[True] for i in range(2, binarySqrt(n)+1): if a[i]: for j in range(i*i, n, i): a[j] = False return [i for i in range(2, n) if a[i]]
>>> eratosthenes1(20)
Slicingandmanyotheroperatorsworkuniformlyonallsequencetypes:strings,tuples,listsIfIisleftout,0istaken;ifJisleftout,len(S)istaken;ifKisleftout,1istaken>>> 'AaBbCcDd'[1:4:2]>>> 'AaBbCcDd'[1::2]>>> 'AaBbCcDd'[:4:2]>>> 'AaBbCcDd'[::2]
Slicingalwaysreturnsanewlist,alsoforS[:]!
Operation Notation
sliceofSfromItoJstepK S[I:J:K]
¡ '0123456'[0:6:1]¡ '0123456'[0:6:2]¡ '0123456'[0:6:3]¡ '0123456'[0:6:4]¡ '0123456'[0:6:5]¡ '0123456'[0:6:6]
¡ '0123456'[0:5:2]¡ '0123456'[0:5:3]¡ '0123456'[0:5:4]¡ '0123456'[0:5:5]¡ '0123456'[0:5:6]
Ingeneral,S[I:J:K]has(J-I-1)//K+1elements
def eratosthenes1(n): a = n*[True] for i in range(2, binarySqrt(n)+1): if a[i]: for j in range(i*i, n, i): a[j] = False return [i for i in range(2, n) if a[i]]Replacingtheinnerforloopwithslicingdef eratosthenes2(n): a = n*[True] for i in range(2, binarySqrt(n)+1): if a[i]: a[i*i: n: i] = \
((n-i*i-1)//i+1)*[False] return [i for i in range(2, n) if a[i]]
add,discard,poparein-situoperations,modifyingtheset
Operation Notation
emptyset set()
setwithE,setwithE,F,… {E}, {E, F}, {E, F, G}
union(∪)ofSandT S|T
intersection(∩)ofSandT S&T
difference(–)ofSandT S-T
cardinalityofS len(S)
EelementofS,notelementofS E in S,E not in S
addEtoS S.add(E)
removeEfromS S.discard(E)
returnandremovearbitraryelement S.pop()
def uniqueElements1(l): s = set() for e in l: s = s|{e} return len(s)
>>> uniqueElements1('abracadabra')>>> uniqueElements1(['Ho', 'Ho', 'Ho'])
Howmuchfasterisin-situinsertion?def uniqueElements2(l): s = set() for e in l: s.add(e) return len(s)
ForlistsL,M,N: ForsetsS,T,U:L+[]=L=[]+L S|set()=S=set()|S (unit)(L+M)+N=L+(M+N) (S|T)|U=S|(T|U) (associativity)
S|T=T|S (commutativity)S|S=S (idempotence)
Tuplesarelikelists,butimmutable,thusnoaliasing,andfaster?def weekday(n): return ['Mon', 'Tue', … , 'Sat', 'Sun'][n]
def weekday(n): return ('Mon', 'Tue', … , 'Sat', 'Sun')[n]
¡ {1, 2} | {2, 3}¡ {1, 2} | {2, 1}¡ {1, 2} & {2, 3}¡ {1, 2} - {2, 3}¡ {2, 3} - {1, 2}¡ set() - {1, 2}¡ s = {2}; s.add(3).add(4); s¡ s = {2}; s.add(3).discard(2); s¡ s = {1, 2, 3}; s.pop()
Lists,strings,tuplesareindexedbyintegers.Dictionariescanbeindexedbyarbitrarytypes.>>> d = {'Jan': 1, 'Feb': 2, 'Mar': 3}
Operation Notation
emptydictionary {}
dictionarymappingkeyEtovalueF,… {E: F}, {E: F, G: H}
lookingupkeyEinD D[E]
keyEinD,keyEnotinD E in S,E not in S
deletingkeyEanditsvaluefromD del D[E]
sizeofD len(D)
Ahistogramdeterminesthe(absolute)frequencyofitemsinacollection.def histogram(s): d = {} for c in s: if c not in d: d[c] = 1 else: d[c] = d[c] + 1 return d
>>> histogram('DOORBELL')>>> histogram([85, 92, 83, 85, 92, 90])
Giventhedenominationsofacurrency,whatistheleastnumberofcoinsneededforagivenamount?Assumethedenominationsaregivenasalistinincreasingorder.def change(a, d): i, r, c = len(d), a, {} while i > 0: i = i - 1 c[d[i]], r = r // d[i], r % d[i] return c
>>> change(57, [1, 5, 10, 25, 100])Thisisanexampleofagreedyalgorithm:pickingthemostcoinsofthehighestdenominationmaynotbeoptimal.When?
¡ Thetop5nomineesforbestanimatedfilm¡ Shoppinglistforpizzaingredientsandamounts¡ Namesofyourcats¡ Thecoursesyoutook,theyearyoutookthem,andthegrade
yougot¡ Alphabeticalclasslist¡ ThewordsofAlice'sAdventureinWonderland:'Down','the',
'rabbit','hole','Alice','was','beginning','to','get','very,'tired'¡ FrequencyofwordsofAlice'sAdventuresinWonderland¡ Financialportfoliowithstocksandamounts¡ Alltheschoolsyouattended