chapter 6djp3.westmont.edu/classes/2016_09_cs010/lectures/lecture_15.pdf · ch06.pptx author:...

25
Chapter 6

Upload: others

Post on 14-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Chapter 6

Page 2: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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:

Page 3: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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

Page 4: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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!=.

Page 5: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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:

Page 6: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Sorting •  Thesort()methodsortsalistofnumbersorstrings.

10/3/16 Page 28

values=[1,16,9,4]values.sort()#Nowvaluesis[1,4,9,16]

Page 7: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Copying Lists •  Asdiscussed,listvariablesdonotthemselvesholdlistelements

•  Theyholdareferencetotheactuallist

•  Ifyoucopythereference,yougetanotherreferencetothesamelist:

10/3/16 Page 29

prices=values

Page 8: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Copying Lists (2) •  Some*mes,youwanttomakeacopyofalist;thatis,anewlistthathasthesameelementsinthesameorderasagivenlist

•  Usethelist()func*on:

10/3/16 Page 30

prices=list(values)

Page 9: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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

Page 10: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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

Page 11: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Common List Functions And Operators

10/3/16 Page 33

Page 12: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Common List Functions And Operators (2)

10/3/16 Page 34

Page 13: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Common List Methods

10/3/16 Page 35

Page 14: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Common List Algorithms SECTION 6.3

10/3/16 Page 36

Page 15: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Common List Algorithms •  FillingaList•  CombiningListElements

•  ElementSeparators

•  MaximumandMinimum

•  LinearSearch

•  Collec*ngandCoun*ngMatches

•  RemovingMatches

•  SwappingElements

•  ReadingInput

10/3/16 Page 37

Page 16: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Filling a List •  Thisloopcreatesandfillsalistwithsquares(0,1,4,9,16,...)

values=[]foriinrange(n):values.append(i*i)

10/3/16 Page 38

Page 17: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Combining List Elements •  Hereishowtocomputeasumofnumbers:

result=0.0forelementinvalues:result=result+element

result=""forelementinnames:result=result+element

10/3/16 Page 39

•  Toconcatenatestrings,youonlyneedtochangetheini*alvalue:

Page 18: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Element Separators •  Whenyoudisplaytheelementsofalist,youusuallywanttoseparatethem,ocenwithcommasorver*callines,likethis:

Harry,Emily,Bob

10/3/16 Page 40

Page 19: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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]

Page 20: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

Element Separators (3) •  Ifyouwanttoprintvalueswithoutaddingthemtoastring:

10/3/16 Page 42

foriinrange(len(values)):ifi>0:print("|",end="")print(values[i],end="")print()

Page 21: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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]

Page 22: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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.

Page 23: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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

Page 24: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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

Page 25: Chapter 6djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture_15.pdf · ch06.pptx Author: Donald Patterson Created Date: 10/3/2016 9:02:59 PM

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.