PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data...

36
PRG – PROGRAMMING ESSENTIALS 1 Lecture 4 – Compound data types, Traversals https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical Engineering, Dept. of Cybernetics, Center for Machine Perception http://cmp.felk.cvut.cz/~reinsmic/ [email protected] 03/12/2017 Michal Reinštein, Czech Technical University in Prague

Transcript of PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data...

Page 1: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

1

PRG– PROGRAMMINGESSENTIALS1

Lecture4– Compounddatatypes,Traversalshttps://cw.fel.cvut.cz/wiki/courses/be5b33prg/start

MichalReinšteinCzechTechnicalUniversityinPrague,

FacultyofElectricalEngineering,Dept.ofCybernetics,CenterforMachinePerceptionhttp://cmp.felk.cvut.cz/~reinsmic/

[email protected]

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

Page 2: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

2

RECAP: MEMORY2

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttps://www.youtube.com/watch?v=arxWaw-E8QQ&t=1s

Page 3: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

3

MOREABOUTPYTHON3

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttps://www.youtube.com/watch?v=arxWaw-E8QQ&t=1s

Page 4: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

4

MOREABOUTPYTHON4

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttps://www.youtube.com/watch?v=arxWaw-E8QQ&t=1s

• Themethodsandvariablesarecreatedonstackmemory• Theobjectsandinstancesarecreatedonheapmemory• Newstackframeiscreatedoninvocationofa

function/method• Stackframesaredestroyedassoonasthe

function/methodreturns• MechanismtocleanupthedeadobjectsisGarbagecollector• EverythinginPythonisobject• Pythonisdynamicallytypedlanguage

Page 5: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

5

TRAVERSAL– THEFORLOOP5

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• Automaterepetitivetaskswithouterrors• Repeatedexecutionofasetofstatementsiscalled iteration• Alreadyexploredfor,nowexplorewhile• Runningthroughallitemsinalistis traversing / traversal

Page 6: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

6

TRAVERSAL– THEWHILELOOP6

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• The while statementhassamemeaningasinEnglish• Evaluatethecondition(atline5)either False or True.• Ifthevalueis False,exitthe while statementandcontinueexecutionatthenextstatement(line8inthiscase)

• Ifthevalueis True,executeeachofthestatementsinthebody(lines6and7),thengobacktothe while statement

Page 7: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

7

TRAVERSAL– THEWHILELOOP7

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• The while loopismoreworkthantheequivalent for loop• Needtomanagetheloopvariable:giveitaninitial value,testforcompletion,updateitinthebodytoenabletermination

• Note: range generatesalistuptobutexcludingthelastvalue

Page 8: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

8

TRAVERSAL– WHILEvs.FOR8

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• Usea for loopifyouknowhowmanytimestheloop willexecute(definiteiteration—weknowaheadsomedefiniteboundsforwhatisneeded)

• Usea for toloopoveriterables (tobeexploredinlaterclasses) usuallyincombinationwithin

• Usewhile loopifyouarerequiredtorepeatcomputationuntilgivenconditionismet,andyoucannotcalculateinadvancewhenthiswillhappen(indefiniteiteration—wedonotknowhowmanyiterationswillbeneeded)

Page 9: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

9

TRAVERSAL– BREAKvs.CONTINUE9

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

Sourcehttp://www.tutorialspoint.com/python/python_loop_control.htm

• The break statementinPythonterminatesthecurrentloopandresumesexecutionatthenextstatement

• The continue statementinPythonreturnsthecontroltothebeginningofthecurrentloop

• The continue statementrejectsalltheremainingstatementsinthecurrentiterationoftheloop…

Page 10: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

10

EXAMPLE10

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• Guessinggame• Thisprogrammakesuseofthemathematicallawof trichotomy (givenrealnumbersaandb,exactlyoneofthesethreemustbetrue:a>b,a<b,ora==b)

Page 11: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

11

COMPOUNDDATATYPES11

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Sofarbuilt-intypeslike int, float, bool• Compounddatatypes:strings,lists,dictionaries,andtuples aredifferentfromtheothersbecausetheyaremadeupofsmallerpieces(charactersincaseofastring,itemsincaseofalist)

• Typescomprisingsmallerpiecesare compounddatatypes

Page 12: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

12

PAIREDDATA12

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• Exampleofpaireddata:listsofnamesandlistsofnumbers• Advancedwayofrepresentingdata:makingapairofthingsisassimpleasputtingthemintoparentheses (i.e.tuples)

Page 13: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

13

NESTEDDATA13

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html

• Datastructure — amechanismforgrouping andorganizingdatatomakeiteasiertouse

Page 14: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

14

TUPLES14

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/tuples.html

• Thepairdataexampleisanexampleofa tuple• Tuplegroupsanynumberofitemsintoacompoundvalue• Tupleisacomma-separatedsequenceofvalues• Otherlanguagesoftencallit records (somerelatedinformationthatbelongstogether)

• Important:stringsandtuplesareimmutable (oncePythoncreatesatupleinmemory,itcannotbechanged)

• Elementsofatuplecannotbemodified,newtupleholdingdifferentinformation shouldalwaysbemadeinstead

Page 15: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

15

TUPLES15

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/tuples.html

• Powerfultupleassignment(remembervariableswapping)• Equivalentofmultipleassignmentstatements• Requirement:thenumberofvariablesontheleftmustmatchthenumberofelementsinthetuple

• Tupleassignmentiscalledtuplepacking /unpacking

Page 16: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

16

TUPLES16

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/tuples.html

• Useoftuplesinfunctionsasreturnvalue• Functioncanalwaysonlyreturnasinglevalue,butbymakingthatvalueatuple,asmanyvaluescanbepackedtogether asisneeded(e.g.findthemeanandthestandarddeviation)

• Tupleitemscanthemselvesbeothertuples(nestedtuples)• Heterogeneousdatastructure:canbecomposedofelementsofdifferenttypes (tuples,strings,lists)

Page 17: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

17

STRINGS17

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Example:upper isamethodthatcanbeinvokedonanystringobjecttocreateanewstring,whereallthecharactersareinuppercase

• lower, capitalize, swapcase …• Usedocumentation&help!

Page 18: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

18

INDEXING18

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Pythonusessquarebracketstoenclosetheindex– indexingoperator []

• Theexpressioninbracketsiscalledan index• Example:Theexpression fruit[1] selectscharacternumber1from fruit,andcreatesanewstringcontainingjustthisonecharacter

• Computerscientistsalwaysstartcountingfromzero!• Anindexspecifiesamemberofanorderedcollection(inthiscasethecollectionofcharactersinthestring)

• Index indicates whichoneyouwant,hencethename• Indexcanbeanyintegerexpression(notonlyvalue)

Page 19: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

19

INDEXING19

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Useenumerate tovisualizeindices• Notethatindexingstringsreturnsa string:Pythonhasnospecialtypeforasinglecharacter(stringoflength=1)

• Useindex toextractelementsfromalist

Page 20: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

20

INDEXING20

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Uselen toextractthenumberofelements(indexingfrom0!)• Negativeindicescountbackwardfromtheendofthestring• Theexpression fruit[-1] yieldsthelastletter• Traversals:while vs.for comparisonagain!

Page 21: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

21

SLICING21

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• A substring ofastringisobtainedbytakinga slice• Slicealisttorefertosomesublist oftheitemsinthelist• Theoperator [n:m] returnsthepartofthestringfromthen’thcharactertothem’th character,includingthefirstbutexcludingthelast(indicespointing between thecharacters)

• Sliceoperator [n:m] copies outthepartofthepaperbetweenthe n andm positions

• Resultof[n:m] willbeoflength(m-n)

Page 22: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

22

SLICING22

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Ifyouomitthefirstindex(beforethecolon),theslicestartsatthebeginningofthestring(orlist)

• Ifyouomitthesecondindex,thesliceextendstotheendofthestring(orlist)

• Ifyouprovidevaluefor n thatisbiggerthanthelengthofthestring(orlist),theslicewilltakeallthevaluesuptotheend

• No“outofrange”errorlikethenormalindexingoperation

Page 23: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

23

STRINGS23

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• Comparingstrings:stringsaresorted inthealphabeticalorder(exceptthatalluppercaseletterscomebeforethelowercase)

• Stringsare immutable(existingstringcannotbechange,newoneshouldbecreatedinstead)

Page 24: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

24

STRINGS24

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• The in /notin operatortestsformembership• Methodindex istheoppositeoftheindexingoperator– ittakesacharacter(itemincaseofalist)andfindstheindexofthecharacter/item(ifnotfoundthenexception israised)

• Methodfind worksforstringsinasimilarway(Ifthecharacterisnotfound,thefunctionreturns -1)

Page 25: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

25

STRINGS25

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• The splitmethod:itsplitsasinglemulti-wordstringintoalistofindividualwords,removingallthewhitespacebetweenthem(whitespaceare:tabs,newlines,spaces)

Page 26: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

26

STRINGS26

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html

• The formatmethodsubstitutesitsargumentsintotheplaceholders(numbersareindexesofthearguments)

• Formatspecification — itisalwaysintroducedbythecolon :• Fieldisalignedtotheleft <,center ^,orright >• Widthallocatedtothefieldwithintheresultstring• Typeofconversion• Specificationofdecimalplaces ( .2f isusefulforworkingwithcurrenciestotwodecimalplaces.)

Page 27: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

27

LISTS27

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html

• A list isanorderedcollectionofvalues• Valuesofalistarecalledits elements or items• Similartostrings(orderedcollectionsofcharacters),exceptthattheelementsofalistcanbeofanytype

• Listsandstrings— andothercollectionsthatmaintaintheorderoftheiritems— arecalled sequences

• Listwithinlistissaidtobe nested• Listwithnoelementsiscalledanempty list,andisdenoted []

Page 28: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

28

LISTS28

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html

• Expressionevaluatingtoanintegercanbeusedasanindex• Functionlen returnslengthofalist(numberofitselements)• Testingmembershipusingin /notin• Operators+ (concatenation)and* (repetition)

Page 29: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

29

LISTS29

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html

• Listsaremutable (wecanchangetheirelements)• Usesameslicingprinciplesasforstrings• Usedel todeletelistelements

Page 30: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

30

REFERENCES– STRINGSvs.LISTS30

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html

• Variables a and b refertostringobjectwithletters "banana”• Useis operatororid functiontofindoutthereference• Stringsare immutable,Pythonoptimizesresourcesbymakingtwonamesthatrefertothesamestringvaluerefertothesameobject

• Notthecaseoflists:a and b havethesamevalue(content)butdonotrefertothesameobject

Strings

Lists

Page 31: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

31

LISTS– ALIASING,CLONING31

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html

• Ifweassignonevariabletoanother,bothvariablesrefertothesameobject

• Thesamelisthastwodifferentnames wesaythatitis aliased (changesmadewithonealiasaffecttheother)

• Recommendation:avoidaliasingwhenyouareworkingwithmutableobjects

• Ifneedtomodifyalistandkeepacopyoftheoriginalusethesliceoperator(takinganysliceof a createsanewlist)

Page 32: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

32

LISTPARAMETERS32

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html

• Passingalistasanargumentpassesareference tothelist,notacopyorcloneofthelist

• Soparameterpassingcreatesanalias

Page 33: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

33

LISTMETHODS33

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

Explorelistmethodsonyourown!SourcebyTomasSvobodaPRG2016/2017

Page 34: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

34

LISTPARAMETERS34

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

• Concept:purefunctionsvs.modifiers• Purefunction doesnotproducesideeffects!• Purefunctioncommunicateswiththecallingprogramonlythroughparameters (itdoesnotmodify)andareturnvalue

• Donotaltertheinputparametersunlessreallynecessary• Programsthatusepurefunctionsarefastertodevelopandlesserror-pronethanprogramsthatusemodifiers

SourcebyTomasSvobodaPRG2016/2017

Page 35: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

35

LISTS– FUNCTIONSPRODUCINGLISTS35

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

SourcebyTomasSvobodaPRG2016/2017

Page 36: PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data types: strings, lists, dictionaries, and tuplesare different from the others because

36

REFERENCES36

03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague

Thislecturere-usesselectedpartsoftheOPENBOOKPROJECTLearningwithPython3(RLE)

http://openbookproject.net/thinkcs/python/english3e/index.htmlavailableunderGNUFreeDocumentationLicense Version1.3)

• Versiondate:October2012• byPeterWentworth,JeffreyElkner,AllenB.Downey,andChrisMeyers

(basedon2ndeditionbyJeffreyElkner,AllenB.Downey,andChrisMeyers)

• Sourcerepositoryisat https://code.launchpad.net/~thinkcspy-rle-team/thinkcspy/thinkcspy3-rle

• Forofflineuse,downloadazipfileofthehtmlorapdfversionfrom http://www.ict.ru.ac.za/Resources/cspw/thinkcspy3/