chapter 6djp3.westmont.edu/classes/2016_09_cs010/lectures/lecture_15.pdf · ch06.pptx author:...
TRANSCRIPT
Chapter 6
Concatenation • Theconcatena*onoftwolistsisanewlistthatcontainstheelementsofthefirstlist,followedbytheelementsofthesecond
myFriends=["Fritz","Cindy"]yourFriends=["Lee","Pat","Phuong"]
ourFriends=myFriends+yourFriends#SetsourFriendsto["Fritz","Cindy","Lee","Pat","Phuong"]
10/3/16 Page 24
• Twolistscanbeconcatenatedbyusingtheplus(+)operator:
Replication • Aswithstringreplica*onoftwolistsisanewlistthatcontainstheelementsofthefirstlist,followedbytheelementsofthesecond
monthInQuarter=[1,2,3]*4
10/3/16 Page 25
monthlyScores=[0]*12
• Resultsinthelist[1,2,3,1,2,3,1,2,3,1,2,3]• Youcanplacetheintegeroneithersideofthe“*”operator
• Theintegerspecifieshowmanycopiesofthelistshouldbeconcatenated
• Onecommonuseofreplica*onistoini*alizealistwithafixedvalue
Equality / Inequality Testing • Youcanusethe==operatortocomparewhethertwolistshavethesameelements,inthesameorder.
[1,4,9]==[1,4,9]#True[1,4,9]==[4,1,9]#False.
[1,4,9]!=[4,9]#True.
10/3/16 Page 26
• Theoppositeof==is!=.
Sum, Maximum, Minimum • Ifyouhavealistofnumbers,thesum()func*onyieldsthesumofallvaluesinthelist.
sum([1,4,9,16])#Yields30
max([1,16,9,4])#Yields16min(["Fred","Ann","Sue”])#Yields"Ann"
10/3/16 Page 27
• Foralistofnumbersorstrings,themax()andmin()func*onsreturnthelargestandsmallestvalue:
Sorting • Thesort()methodsortsalistofnumbersorstrings.
10/3/16 Page 28
values=[1,16,9,4]values.sort()#Nowvaluesis[1,4,9,16]
Copying Lists • Asdiscussed,listvariablesdonotthemselvesholdlistelements
• Theyholdareferencetotheactuallist
• Ifyoucopythereference,yougetanotherreferencetothesamelist:
10/3/16 Page 29
prices=values
Copying Lists (2) • Some*mes,youwanttomakeacopyofalist;thatis,anewlistthathasthesameelementsinthesameorderasagivenlist
• Usethelist()func*on:
10/3/16 Page 30
prices=list(values)
Slices of a List • Some*mesyouwanttolookatapartofalist.Supposeyouaregivenalistoftemperatures,onepermonth:
temperatures=[18,21,24,33,39,40,39,36,30,22,18]
• Youareonlyinterestedinthetemperaturesforthethirdquarter,withindexvalues6,7,and8
• Youcanusethesliceoperatortoobtainthem:
thirdQuarter=temperatures[6:9]
• Theargumentsarethefirstelementtoinclude,andthefirsttoexclude• Soinourexamplewegetelements6,7,and8
10/3/16 Page 31
Slices (2) • Bothindexesusedwiththesliceoperatorareop*onal• IfthefirstindexisomiYed,allelementsfromthefirstareincluded
• Theslicetemperatures[:6]
• Includesallelementsupto,butnotincluding,posi*on6
• Theslicetemperatures[6:]
• Includesallelementsstar*ngatposi*on6totheendofthelist
• Youcanassignvaluestoaslice:temperatures[6:9]=[45,44,40]
• Replacesthevaluesinelements6,7,and8
10/3/16 Page 32
Common List Functions And Operators
10/3/16 Page 33
Common List Functions And Operators (2)
10/3/16 Page 34
Common List Methods
10/3/16 Page 35
Common List Algorithms SECTION 6.3
10/3/16 Page 36
Common List Algorithms • FillingaList• CombiningListElements
• ElementSeparators
• MaximumandMinimum
• LinearSearch
• Collec*ngandCoun*ngMatches
• RemovingMatches
• SwappingElements
• ReadingInput
10/3/16 Page 37
Filling a List • Thisloopcreatesandfillsalistwithsquares(0,1,4,9,16,...)
values=[]foriinrange(n):values.append(i*i)
10/3/16 Page 38
Combining List Elements • Hereishowtocomputeasumofnumbers:
result=0.0forelementinvalues:result=result+element
result=""forelementinnames:result=result+element
10/3/16 Page 39
• Toconcatenatestrings,youonlyneedtochangetheini*alvalue:
Element Separators • Whenyoudisplaytheelementsofalist,youusuallywanttoseparatethem,ocenwithcommasorver*callines,likethis:
Harry,Emily,Bob
10/3/16 Page 40
Element Separators (2) • Addtheseparatorbeforeeachelement(there’sonefewerseparatorthantherearenumbers)inthesequenceexcepttheini*alone(withindex0),likethis:
10/3/16 Page 41
foriinrange(len(names)):ifi>0:result=result+","result=result+names[i]
Element Separators (3) • Ifyouwanttoprintvalueswithoutaddingthemtoastring:
10/3/16 Page 42
foriinrange(len(values)):ifi>0:print("|",end="")print(values[i],end="")print()
Maximum and Minimum • Hereistheimplementa*onofthemaxalgorithm(alreadycoveredinChapter4,thisoneisjustspecifictoalist):
10/3/16 Page 43
largest=values[0]foriinrange(1,len(values)):ifvalues[i]>largest:largest=values[i]
smallest=values[0]foriinrange(1,len(values)):ifvalues[i]<smallest:smallest=values[i]
Linear Search • Findingthefirstvaluethatis>100.Youneedtovisitallelementsun*lyouhavefoundamatchoryouhavecometotheendofthelist:
10/3/16 Page 44
limit=100pos=0found=Falsewhilepos<len(values)andnotfound:ifvalues[pos]>limit:found=Trueelse:pos=pos+1iffound:print("Foundatposition:",pos)else:print("Notfound")
A linear search inspects elements in sequence until a match is found.
Collecting and Counting Matches • Collec*ngallmatches
10/3/16 Page 45
limit=100result=[]forelementinvalues:if(element>limit):result.append(element)
limit=100counter=0forelementinvalues:if(element>limit):counter=counter+1
• Coun*ngmatches
Removing Matches • Removeallelementsthatmatchapar*cularcondi*on
• Example:removeallstringsoflength<4fromalist
10/3/16 Page 46
i=0whilei<len(words):word=words[i]iflen(word)<4:words.pop(i)else:i=i+1
Swapping Elements • Forexample,youcansortalistbyrepeatedlyswappingelementsthatarenotinorder
• Swaptheelementsatposi*onsiandjofalistvalues
• We’dliketosetvalues[i]tovalues[j].Butthatoverwritesthevaluethatiscurrentlystoredinvalues[i],sowewanttosavethatfirst:
10/3/16 Page 47
Before moving a new value into a location (say blue) copy blue’s value elsewhere and then move black’s value into blue. Then move the temporary value (originally in blue) into black.