PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data...
Transcript of PRG –PROGRAMMING ESSENTIALS€¦ · •So far built-in types likeint,float,bool •Compound data...
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/
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
2
RECAP: MEMORY2
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttps://www.youtube.com/watch?v=arxWaw-E8QQ&t=1s
3
MOREABOUTPYTHON3
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttps://www.youtube.com/watch?v=arxWaw-E8QQ&t=1s
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
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
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
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
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)
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…
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)
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
12
PAIREDDATA12
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html
• Exampleofpaireddata:listsofnamesandlistsofnumbers• Advancedwayofrepresentingdata:makingapairofthingsisassimpleasputtingthemintoparentheses (i.e.tuples)
13
NESTEDDATA13
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/iteration.html
• Datastructure — amechanismforgrouping andorganizingdatatomakeiteasiertouse
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
15
TUPLES15
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/tuples.html
• Powerfultupleassignment(remembervariableswapping)• Equivalentofmultipleassignmentstatements• Requirement:thenumberofvariablesontheleftmustmatchthenumberofelementsinthetuple
• Tupleassignmentiscalledtuplepacking /unpacking
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)
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!
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)
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
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!
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)
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
23
STRINGS23
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/strings.html
• Comparingstrings:stringsaresorted inthealphabeticalorder(exceptthatalluppercaseletterscomebeforethelowercase)
• Stringsare immutable(existingstringcannotbechange,newoneshouldbecreatedinstead)
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)
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)
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.)
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 []
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)
29
LISTS29
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html
• Listsaremutable (wecanchangetheirelements)• Usesameslicingprinciplesasforstrings• Usedel todeletelistelements
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
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)
32
LISTPARAMETERS32
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
sourcehttp://openbookproject.net/thinkcs/python/english3e/lists.html
• Passingalistasanargumentpassesareference tothelist,notacopyorcloneofthelist
• Soparameterpassingcreatesanalias
33
LISTMETHODS33
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
Explorelistmethodsonyourown!SourcebyTomasSvobodaPRG2016/2017
34
LISTPARAMETERS34
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
• Concept:purefunctionsvs.modifiers• Purefunction doesnotproducesideeffects!• Purefunctioncommunicateswiththecallingprogramonlythroughparameters (itdoesnotmodify)andareturnvalue
• Donotaltertheinputparametersunlessreallynecessary• Programsthatusepurefunctionsarefastertodevelopandlesserror-pronethanprogramsthatusemodifiers
SourcebyTomasSvobodaPRG2016/2017
35
LISTS– FUNCTIONSPRODUCINGLISTS35
03/12/2017 MichalReinštein,CzechTechnicalUniversityinPrague
SourcebyTomasSvobodaPRG2016/2017
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/