版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
(Python引 Python入 算法分 “大O”表示 列表 字典 棧 抽象數(shù)據(jù)類型 用Python實現(xiàn) 抽象數(shù)據(jù)類型 在Python中實現(xiàn) Python實 討 抽象數(shù)據(jù)類型 在Python中實現(xiàn) 抽象數(shù)據(jù)類型無序列表Unordered 遞歸 4.4.1.斯基三角形Sierpinski 散 術(shù)語 定 二叉堆BinaryHeap實現(xiàn)的優(yōu)先隊 建立WordLadder Dijkstra算 Dijkstra算法分 Prim最小生成樹算 小 引PythonThewaywethinkaboutprogramminghasundergonemanychangesintheyearssincethefirstelectroniccomputersrequiredpatchcablesandswitchestoconveyinstructionsfromhumantomachine.Asisthecasewithmanyaspectsofsociety,changesincomputingtechnologyprovidecomputerscientistswithagrowingnumberoftoolsandplatformsonwhichtopracticetheircraft.Advancessuchasfasterprocessors,high-speednetworks,andlargememorycapacitieshavecreatedaspiralofcomplexitythroughwhichcomputerscientistsmustnavigate.Throughoutallofthisrapidevolution,anumberofbasicprincipleshaveremainedconstant.Thescienceofcomputingisconcernedwithusingcomputerstosolveproblems.Youhavenodoubtspentconsiderabletimelearningthebasicsofproblem-solvingandhopefullyfeelconfidentinyourabilitytotakeaproblemstatementanddevelopasolution.Youhavealsolearnedthatwritingcomputerprogramsisoftenhard.Thecomplexityoflargeproblemsandthecorrespondingcomplexityofthesolutionscantendtoovershadowthefundamentalideasrelatedtotheproblem-solvingprocess.Thischapteremphasizestwoimportantareasfortherestofthetext.First,itreviewstheframeworkwithinwhichcomputerscienceandthestudyofalgorithmsanddatastructuresmustfit,inparticular,thereasonswhyweneedtostudythesetopicsandhowunderstandingthesetopicshelpsusto ebetterproblemsolvers.Second,wereviewthePythonprogramminglanguage.Althoughwecannotprovideadetailed,exhaustivereference,wewillgiveexamplesandexplanationsforthebasicconstructsandideasthatwilloccurthroughouttheremainingchapters.Computerscienceisoftendifficulttodefine.Thisisprobablyduetotheunfortunateuseoftheword“computer”inthename.Asyouareperhapsaware,computerscienceisnotsimplythestudyofcomputers.Althoughcomputersplayanimportantsupportingroleasatoolinthediscipline,theyarejustthat–tools.Computerscienceisthestudyofproblems,problem-solving,andthesolutionsthatcomeoutoftheproblem-solvingprocess.Givenaproblem,acomputerscientist’sgoalistodevelopanalgorithm,astep-by-steplistofinstructionsforsolvinganyinstanceoftheproblemthatmightarise.Algorithmsarefiniteprocessesthatiffollowedwillsolvetheproblem.AlgorithmsareComputersciencecanbethoughtofasthestudyofalgorithms.However,wemustbecarefultoincludethefactthatsomeproblemsmaynothaveasolution.Althoughprovingthisstatementisthescopeofthistext,thefactthatsomeproblemscannotbesolvedisimportantforthosewhostudycomputerscience.Wecanfullydefinecomputerscience,then,byincludingbothtypesofproblemsandstatingthatcomputerscienceisthestudyofsolutionstoproblemsaswellasthestudyofproblemswithnosolutions.Itisalsoverycommontoincludethewordcomputablewhendescribingproblemsandsolutions.Wesaythataproblemiscomputableifgorithmexistsforsolvingit.ternativedefinitionforcomputerscience,then,istosaythatcomputerscienceisthestudyofproblemsthatareandthatarenotcomputable,thestudyoftheexistenceandthenonexistenceofalgorithms.Inanycase,youwillnotethattheword“computer”didnotcomeupatall.Solutionsareconsideredindependentfromthemachine.Computerscience,asitpertainstotheproblem-solvingprocessitself,isalsothestudyof ionallowsustoviewtheproblemandsolutioninsuchawayastotheso-calledlogicaland s.ThebasicideaisfamiliartousinaConsidertheautomobilethatyoumayhavedriventoschoolorworktoday.Asadriver,auserofthecar,youhavecertaininteractionsthattakeplaceinordertoutilizethecarforitsintendedpurpose.Yougetin,insertthekey,startthecar,shift,brake,accelerate,andsteerinordertodrive.Froman ionpointofview,wecansaythatyouareseeingthelogicaloftheautomobile.Youareusingthefunctionsprovidedbythecardesignersforthepurposeoftransportingyoufromonelocationtoanother.Thesefunctionsaresometimesalsoreferredtoastheinterface.Ontheotherhand,themechanicwhomustrepairyourautomobiletakesaverydifferentpointofview.Shenotonlyknowshowtodrivebutmustknowallofthedetailsnecessarytocarryoutallthefunctionsthatwetakeforgranted.Sheneedstounderstandhowtheengineworks,howthetransmissionshiftsgears,howtemperatureiscontrolled,andsoon.Thisisknownasthephysical,thedetailsthattakeplace“underthehood.”Thesamethinghappenswhenweusecomputers.Mostpeopleusecomputerstowrite sendandreceive ,surftheweb,playmusic,storeimages,andplaygameswithoutanyknowledgeofthedetailsthattakeplacetoallowthosetypesofapplicationstowork.Theyviewcomputersfromalogicaloruser.Computerscientists,programmers,technologysupportstaff,andsystemadministratorstakeaverydifferentviewofthecomputer.Theymustknowthedetailsofhowoperatingsystemswork,hownetworkprotocolsareconfigured,andhowtocodevariousscriptsthatcontrolfunction.Theymustbeabletocontrolthelow-leveldetailsthatausersimplyassumes.Thecommonpointforbothoftheseexamplesisthattheuserofthe ion,sometimesalsocalledtheclient,doesnotneedtoknowthedetailsaslongastheuserisawareofthewaytheinterfaceworks.Thisinterfaceisthewayweasuserscommunicatewiththeunderlyingcomplexitiesoftheimplementation.Asanotherexampleof ion,considerthePythonmathmodule.Onceweimportthemodule,wecanperformcomputationssuchas>>>>>>import>>>math.sqrt(16)Thisisanexampleofprocedural ion.Wedonotnecessarilyknowhowthesquarerootisbeingcalculated,butweknowwhatthefunctioniscalledandhowtouseit.Iferformtheimportcorrectly,wecanassumethatthefunctionwillprovideuswiththecorrectresults.Weknowthatsomeoneimplementedasolutiontothesquarerootproblembutweonlyneedtoknowhowtouseit.Thisissometimesreferredtoasa“blackbox”viewofaprocess.Wesimplydescribetheinterface:thenameofthefunction,whatisneeded(theparameters),andwhatwillbereturned.Thedetailsarehiddeninside(seeFigure1).圖1 Programmingistheprocessoftakinggorithmandencodingitintoanotation,aprogramminglanguage,sothatitcanbeexecutedbyacomputer.Althoughmanyprogramminglanguagesandmanydifferenttypesofcomputersexist,theimportantfirststepistheneedtohavethesolution.Withoutgorithmtherecanbenoprogram.Computerscienceisnotthestudyofprogramming.Programming,however,isanimportantpartofwhomputerscientistdoes.Programmingisoftenthewaythatwecreatearepresentationforoursolutions.Therefore,thislanguagerepresentationandtheprocessofcreatingit esafundamentalpartofthediscipline.Algorithmsdescribethesolutiontoaproblemintermsofthedataneededtorepresenttheprobleminstanceandthesetofstepsnecessarytoproducetheintendedresult.Programminglanguagesmustprovideanotationalwaytorepresentboththeprocessandthedata.Tothisend,languagesprovidecontrolconstructsanddatatypes.Controlconstructsallowalgorithmicstepstoberepresentedinaconvenientyetunambiguousway.Ataminimum,algorithmsrequireconstructsthatperformsequentialprocessing,selectionfordecision-making,anditerationforrepetitivecontrol.Aslongasthelanguageprovidesthesebasicstatements,itcanbeusedforalgorithmrepresentation.Alldataitemsinthecomputerarerepresentedasstringsofbinarydigits.Inordertogivethesestringsmeaning,weneedtohavedatatypes.Datatypesprovideaninterpretationforthisbinarydatasothatwecanthinkaboutthedataintermsthatmakesensewithrespecttotheproblembeingsolved.Theselow-level,built-indatatypes(sometimescalledtheprimitivedatatypes)providethebuildingblocksforalgorithmdevelopment.Forexample,mostprogramminglanguagesprovideadatatypeforintegers.Stringsofbinarydigitsinthecomputer’smemorycanbeinterpretedasintegersandgiventhetypicalmeaningsthatwecommonlyassociatewithintegers(e.g.23,654,and-19).Inaddition,adatatypealsoprovidesadescriptionoftheoperationsthatthedataitemscanparticipatein.Withintegers,operationssuchasaddition,subtraction,andmultiplicationarecommon.Wehavecometoexpectthatnumerictypesofdanparticipateinthesearithmeticoperations.ThedifficultythatoftenarisesforusisthefactthatproblemsandtheirsolutionsareveryThesesimple,language-providedconstructsanddatatypes,althoughcertainlysufficienttorepresentcomplexsolutions,aretypicallyatadisadvantageasweworkthroughtheproblem-solvingprocess.WeneedwaystocontrolthiscomplexityandassistwiththecreationofTomanagethecomplexityofproblemsandtheproblem-solvingprocess,computerscientistsuseionstoallowthemtofocusonthe“bigpicture”withoutgettinglostinthedetails.Bycreatingmodelsoftheproblem ,weareabletoutilizeabetterandmoreefficientproblem-solvingprocess.Thesemodelsallowustodescribethedatathatouralgorithmsmanipulateina oreconsistentwaywithrespecttotheproblemEarlier,wereferredtoprocedural ionasaprocessthathidesthedetailsofaparticularfunctiontoallowtheuserorclienttoviewitataveryhighlevel.Wenowturnourattentiontoasimilaridea,thatofdata ion.An datatype,sometimesabbreviatedADT,isalogicaldescriptionofhowweviewthedataandtheoperationsthatareallowedwithoutregardtohowtheywillbeimplemented.Thismeansthatweareconcernedonlywithwhatthedataisrepresentingandnotwithhowitwilleventuallybeconstructed.Byprovidingthislevelofion,wearecreatinganencapsulationaroundthedata.Theideaisthatbyencapsulatingthedetailsoftheimplementation,wearehidingthemfromtheuser’sview.ThisisinformationFigure2showsapictureofwhatan datatypeisandhowitoperates.Theuserinteractswiththeinterface,usingtheoperationsthathavebeenspecifiedbythe datatype.Thedatatypeisthesthattheuserinteractswith.Theimplementationishiddenoneleveldeeper.Theuserisnotconcernedwiththedetailsofthe圖 DataTheimplementationofan datatype,oftenreferredtoasadatastructure,willrequirethatweprovideaphysicalviewofthedatausingsomecollectionofprogrammingconstructsandprimitivedatatypes.Aswediscussedearlier,theseparationofthesetwoswillallowustodefinethecomplexdatamodelsforourproblemswithoutgivinganyindicationastothedetailsofhowthemodelwillactuallybebuilt.Thisprovidesanimplementation-independentviewofthedata.Sincetherewillusuallybemanydifferentwaystoimplementan datatype,thisimplementationindependenceallowstheprogrammertoswitchthedetailsoftheimplementationwithoutchangingthewaytheuserofthedatainteractswithit.Theusercanremainfocusedontheproblem-solvingprocess.Computerscientistslearnbyexperience.Welearnbyseeingotherssolveproblemsandbysolvingproblemsbyourselves.Beingexposedtodifferentproblem-solvingtechniquesandseeinghowdifferentalgorithmsaredesignedhelpsustotakeonthenextchallengingproblemthatwearegiven.Byconsideringanumberofdifferentalgorithms,wecanbegintodeveloppatternrecognitionsothatthenexttimeasimilarproblemarises,wearebetterabletosolveit.Algorithmsareoftenquitedifferentfromoneanother.Considertheexampleofsqrtseenearlier.Itisentirelypossiblethattherearemanydifferentwaystoimplementthedetailstocomputethesquarerootfunction.Onealgorithmmayusemanyfewerresourcesthananother.Onealgorithmmighttake10timesaslongtoreturntheresultastheother.Wewouldliketohavesomewaytocomparethesetwosolutions.Eventhoughtheybothwork,oneisperhaps“better”thantheother.Wemightsuggestthatoneismoreefficientorthatonesimplyworksfasteroruseslessmemory.Aswestudyalgorithms,wecanlearnysistechniquesthatallowustocompareandcontrastsolutionsbasedsolelyontheirowncharacteristics,notthecharacteristicsoftheprogramorcomputerusedtoimplementthem.Intheworstcasescenario,wemayhaveaproblemthatisintractable,meaningthatthereisnoalgorithmthatcansolvetheprobleminarealisticamountoftime.Itisimportanttobeabletodistinguishbetweenthoseproblemsthathavesolutions,thosethatdonot,andthosewheresolutionsexistbutrequiretoomuchtimeorotherresourcestoworkreasonably.Therewilloftenbetrade-offsthatwewillneedtoidentifyanddecideupon.Ascomputerscientists,inadditiontoourabilitytosolveproblems,wewillalsoneedtoknowandunderstandsolutionevaluationtechniques.In,thereareoftenmanywaystosolveaproblem.Findingasolutionandthendecidingwhetheritisagoodonearetasksthatwewilldooverandoveragain.PythonInthissection,wewillreviewtheprogramminglanguagePythonandalsoprovidesomemoredetailedexamplesoftheideasfromtheprevioussection.IfyouarenewtoPythonorfindthatyouneedmoreinformationaboutanyofthetopicspresented, mendthatyouconsultresourcesuchasthePythonLanguageReferenceoraPythonTutorial.Ourgoalhereistoreacquaintyouwiththelanguageandalsoreinforcesomeoftheconceptsthatwillbecentraltolaterchapters.Pythonisamodern,easy-to-learn,object-orientedprogramminglanguage.Ithasapowerfulsetofbuilt-indatatypesandeasy-to-usecontrolconstructs.SincePythonisaninterpretedlanguage,itismosteasilyreviewedbysimplylookingatanddescribinginteractivesessions.Youshouldrecallthattheinterpreterdisplaysthefamiliar>>>promptandthenevaluatesthePythonconstructthatyouprovide.Forexample,>>>>>>print("AlgorithmsandDataStructures")AlgorithmsandDataStructuresshowstheprompt,theprintfunction,theresult,andthenextWestatedabovethatPythonsupportstheobject-orientedprogrammingparadigm.ThismeansthatPythonconsidersdatatobethefocalpointoftheproblem-solvingprocess.InPython,aswellasinanyotherobject-orientedprogramminglanguage,wedefineaclasstobeadescriptionofwhatthedatalooklike(thestate)andwhatthedando(thebehavior).Classesareogoustodatatypesbecauseauserofaclassonlyseesthestateandbehaviorofadataitem.Dataitemsarecalledobjectsintheobject-orientedparadigm.Anobjectisaninstanceofaclass.內(nèi)建原子數(shù)據(jù)類Wewillbeginourreviewbyconsideringtheatomicdatatypes.Pythonhastwomainbuilt-innumericclassesthatimplementtheintegerandfloatingpointdatatypes.ThesePythonclassesarecalledintandfloat.Thestandardarithmeticoperations,+,-,*,/,and**(exponentiation),canbeusedwithparenthesesforcingtheorderofoperationsawayfromnormaloperatorprecedence.Otherveryusefuloperationsaretheremainder(modulo)operator,%,andintegerdivision,//.Notethatwhentwointegersaredivided,theresultisafloatingpoint.Theintegerdivisionoperatorreturnstheintegerportionofthequotientbytruncatinganyfractionalpart.print2+3*4printprint2+3*4print(2+3)*4print2**10print6/3print7/3print7//3printprint3/6print3//6print3%6printprint3/6print3//6print3%6print2**100Thebooleandatatype,implementedasthePythonboolclass,willbequiteusefulforrepresentingtruthvalues.ThepossiblestatevaluesforabooleanobjectareTrueandFalsewiththestandardbooleanoperators,and,or,andnot.>>>>>>True>>>False>>>FalseorTrue>>>not(FalseorTrue)>>>TrueandTrue1BasicArithmeticOperatorsBooleandataobjectsarealsousedasresultsforcomparisonoperatorssuchasequality(==)andgreaterthan(>).Inaddition,relationaloperatorsandlogicaloperatorscanbecombinedtogethertoformcomplexlogicalquestions.Table1showstherelationalandlogicaloperatorswithexamplesshowninthesessionthatfollows.Operationless<Lessthangreater>GreaterthanlessthanorLessthanorequaltogreaterthanorGreaterthanorequaltoEqualitynotNotequallogicalBothoperandsTrueforresulttobelogicalOneortheotheroperandisTruefortheresulttobelogicalNegatesthetruthvalue, esTrue,es1RelationalandLogicalprint(10>print((5print((5>=1)and(5<=2BasicRelationalandLogicalOperatorsIdentifiersareusedinprogramminglanguagesasnames.InPython,identifiersstartwithaletteroranunderscore(_),arecasesensitive,andcanbeofanylength.RememberthatitisalwaysagoodideatousenamesthatconveymeaningsothatyourprogramcodeiseasiertoreadandAPythonvariableiscreatedwhenanameisusedforthefirsttimeontheleft-handsideofanassignmentstatement.Assignmentstatementsprovideawaytoassociateanamewithavalue.Thevariablewillholdareferencetoapieceofdataandnotthedataitself.Considerthefollowing>>>>>>theSum=>>>theSum>>>theSum=theSum+>>>theSum>>>theSum=>>>theSumTheassignmentstatementtheSum=0createsavariablecalledtheSumandletsitholdthereferencetothedataobject0(seeFigure3).Ingeneral,theright-handsideoftheassignmentstatementisevaluatedandareferencetotheresultingdataobjectis“assigned”tothenameontheleft-handside.Atthispointinourexample,thetypeofthevariableisintegerasthatisthetypeofthedurrentlybeingreferredtobythesum.Ifthetypeofthedhanges(seeFigure4),asshownabovewiththebooleanvalueTrue,sodoesthetypeofthevariable(thesumisnowofthetypeboolean).Theassignmentstatementchangesthereferencebeingheldbythevariable.ThisisadynamiccharacteristicofPython.Thesamevariablecanrefertomanydifferenttypesofdata.3VariablesHoldReferencestoData4AssignmentChangesthe內(nèi)建集合數(shù)據(jù)類Inadditiontothenumericandbooleanclasses,Pythonhasanumberofverypowerfulbuilt-incollectionclasses.Lists,strings,andtuplesareorderedcollectionsthatareverysimilaringeneralstructurebuthavespecificdifferencesthatmustbeunderstoodforthemtobeusedproperly.Setsanddictionariesareunorderedcollections.AlistisanorderedcollectionofzeroormorereferencestoPythondataobjects.Listsarewrittenascomma-delimitedvaluesenclosedinsquarebrackets.Theemptylistissimply[].Listsareheterogeneous,meaningthatthedataobjectsneednotallbefromthesameclassandthecollectioncanbeassignedtoavariableasbelow.ThefollowingfragmentshowsavarietyofPythondataobjectsinalist.>>>>>>[1,3,True,>>>myList=>>>[1,3,True,NotethatwhenPythonevaluatesalist,thelistitselfisreturned.However,inordertorememberthelistforlaterprocessing,itsreferenceneedstobeassignedtoavariable.Sincelistsareconsideredtobesequentiallyordered,theysupportanumberofoperationsthatcanbeappliedtoanyPythonsequence.Table2reviewstheseoperationsandthefollowingsessiongivesexamplesoftheiruse.Operation[Accessanelementofa+Combinesequences*ConcatenatearepeatednumberofAskwhetheranitemisinaAskthenumberofitemsinthe[:Extractapartofa2OperationsonAnySequenceinNotethattheindicesforlists(sequences)startcountingwith0.Thesliceoperation,myList[1:3],returnsalistofitemsstartingwiththeitemindexedby1uptobutnotincludingtheitemindexedby3.Sometimes,youwillwanttoinitializealist.Thiscanquicklybe plishedbyusingrepetition.Forexample,>>>>>>myList=[0]*>>>[0,0,0,0,0,Oneveryimportantasiderelatingtotherepetitionoperatoristhattheresultisarepetitionofreferencestothedataobjectsinthesequence.ThiscanbestbeseenbyconsideringthefollowingmyListmyList=[1,2,3,4]A=[myList]*33RepetitionofReferencesThevariableAholdsacollectionofthreereferencestotheoriginallistcalledmyList.NotethatachangetooneelementofmyListshowsupinallthreeoccurrencesinA.Listssupportanumberofmethodsthatwillbeusedtobuilddatastructures.Table3providesasummary.Examplesoftheirusefollow.MethodAddsanewitemtoofaInsertsanitemattheithpositioninaRemovesandreturnsthelastiteminaRemovesandreturnstheithiteminaModifiesalisttobeModifiesalisttobeinreversedelDeletestheitemintheithReturnstheindexofthefirstoccurrenceofReturnsthenumberofoccurrencesofRemovesthefirstoccurrenceof3MethodsProvidedbyListsinmyListmyList=[1024,3,True,6.5]delmyList[0]4ExamplesofListMethodsYoucanseethatsomeofthemethods,suchaspop,returnavalueandalsomodifythelist.Others,suchasreverse,simplymodifythelistwithnoreturnvalue.popwilldefaultto ofthelistbutcsoremoveandreturnaspecificitem.Theindexrangestartingfrom0isagainusedforthesemethods.Youshouldalsonoticethefamiliar“dot”notationforaskinganobjecttoinvokeamethod.myList.append(False)canbereadas“asktheobjectmyListtoperformitsappendmethodandsenditthevalueFalse.”Evensimpledataobjectssuchasintegerscaninvokemethodsinthisway.>>>>>>(54).add(21)Inthisfragmentweareaskingtheintegerobject54toexecuteitsaddmethod(called Python)andpassingit21asthevaluetoadd.Theresultisthesum,75.Ofcourse,weusuallywritethisas54+21.Wewillsaymu oreaboutthesemethodslaterinthissection.OnecommonPythonfunctionthatisoftendiscussedinconjunctionwithlistsistherangefunction.rangeproducesarangeobjectthatrepresentsasequenceofvalues.Byusingthelistfunction,itispossibletoseethevalueoftherangeobjealist.Thisisillustratedbelow.>>>>>>range(10)range(0,10)>>>[0,1,2,3,4,5,6,7,8,>>>range(5,10)range(5,10)>>>list(range(5,10))[5,6,7,8,9]>>>list(range(5,10,2))[5,7,9]>>>list(range(10,1,-1))[10,9,8,7,6,5,4,3,2]Therangeobjectrepresentsasequenceofintegers.Bydefault,itwillstartwith0.Ifyouprovidemoreparameters,itwillstartandendatparticularpointsandcanevenskipitems.Inourfirstexample,range(10),thesequencestartswith0andgoesuptobutdoesnotinclude10.Inoursecondexample,range(5,10)startsat5andgoesuptobutnotincluding10.range(5,10,2)performssimilarlybutskipsbytwos(again,10isnotincluded).Stringsaresequentialcollectionsofzeroormoreletters,numbersandothersymbols.Wecalltheseletters,numbersandothersymbolscharacters.Literalstringvaluesaredifferentiatedfromidentifiersbyusingquotationmarks(eithersingleordouble).>>>>>>"David">>>myName=>>>myName[3]>>>myName*2>>>len(myName)Sincestringsaresequences,allofthesequenceoperationsdescribedaboveworkasyouexpect.Inaddition,stringshaveanumberofmethods,someofwhichareshowninTable4.For>>>>>>myName>>>myName.upper()>>>myName.center(10)'David >>>myName.find('v')>>>myName.split('v')['Da','id']Ofthese,splitwillbeveryusefulforprocessingdata.splitwilltakeastringandreturnalistofstringsusingthesplitcharacterasadivisionpoint.Intheexample,visthedivisionpoint.Ifnodivisionisspecified,thesplitmethodlooksforwhitespacecharacterssuchastab,newlineandMethodReturnsastringcenteredinafieldofsizeReturnsthenumberofoccurrencesofiteminReturnsastringleft-justifiedinafieldofsizeReturnsastringinallReturnsastringright-justifiedinafieldofwReturnstheindexofthefirstoccurrenceofSplitsastringintosubstringsat4MethodsProvidedbyStringsinAmajordifferencebetweenlistsandstringsisthatlistscanbemodifiedwhilestringscannot.Thisisreferredtoasmutability.Listsaremutable;stringsareimmutable.Forexample,youcanchangeaniteminalistbyusingindexingandassignment.Withastringthatchangeisnot>>>>>>[1,3,True,>>>>>>[1024,3,True,>>>>>>Traceback(mostrecentcallFile"<pys #84>",line1,in-toplevel-TypeError:objectdoesn'tsupportitemTuplesareverysimilartolistsinthattheyareheterogeneoussequencesofdata.Thedifferenceisthatatupleisimmutable,likeastring.Atuplecannotbechanged.Tuplesarewrittenascomma-delimitedvaluesenclosedinparentheses.Assequences,theycanuseanyoperationdescribedabove.Forexample,>>>>>>myTuple=>>>(2,True,>>>len(myTuple)>>>myTuple[0]>>>myTuple*(2,True,4.96,2,True,4.96,2,True,>>>myTuple[0:2](2,True)However,ifyoutrytochangeaniteminatuple,youwillgetanerror.Notethattheerrormessageprovideslocationandreasonfortheproblem.>>>>>>Traceback(mostrecentcallFile"<pys #137>",line1,in-toplevel-TypeError:objectdoesn'tsupportitemAsetisanunorderedcollectionofzeroormoreimmutablePythondataobjects.Setsdonotallowduplicatesandarewrittenascomma-delimitedvaluesenclosedincurlybraces.Theemptysetisrepresentedbyset().Setsareheterogeneous,andthecollectioncanbeassignedtoavariableas>>>>>>{False,4.5,3,6,>>>mySet=>>>{False,4.5,3,6,Eventhoughsetsarenotconsideredtobesequential,theydosupportafewofthefamiliaroperationspresentedearlier.Table5reviewstheseoperationsandthefollowingsessiongivesexamplesoftheiruse.OperationSetReturnsthecardinalityofthe|aset|Returnsanewsetwithallelementsfromboth&aset&Returnsanewsetwithonlythoseelementstoboth-aset-Returnsanewsetwithallitemsfromthefirstsetinaset<=Askswhetherallelementsofthefirstsetarein5OperationsonaSetin>>>>>>{False,4.5,3,6,>>>len(mySet)>>>FalseinmySet>>>"dog"inmySetSetssupportanumberofmethodsthatshouldbefamiliartothosewhohaveworkedwiththeminamathematicssetting.Table6providesasummary.Examplesoftheirusefollow.Notethatunion,intersection,issubset,anddifferenceallhaveoperatorsthatcanbeusedasMethodReturnsanewsetwithallelementsbothReturnsanewsetwithonlyelementscommontobothReturnsanewsetwithallitemsfirstsetnotinAskswhetherallelementsofonesetintheAddsitemtotheRemovesitemfromtheRemovesanarbitraryelementfromRemovesallelementsfromthe6MethodsProvidedbySetsin>>>>>>{False,4.5,3,6,>>>yourSet=>>>{False,4.5,3,100,6,'cat',>>>mySet|{False,4.5,3,100,6,'cat',>>>>>>mySet&>>>{False,4.5,6,>>>mySet-{False,4.5,6,>>>{3,100}.issubset(yourSet)>>>{3,100}<=yourSet>>>>>>{False,4.5,3,6,'house',>>>>>>{False,3,6,'house',>>>mySet.pop()>>>{3,6,'house',>>>>>>OurfinalPythoncollectionisanunorderedstructurecalledadictionary.Dictionariesarecollectionsofassociatedpairsofitemswhereeachpairconsistsofakeyandavalue.Thiskey-valuepairistypicallywrittenaskey:value.Dictionari
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 電氣工程及其自動化專業(yè)介紹
- 2024連鎖餐飲企業(yè)與食材供應(yīng)商的供貨合同
- 數(shù)控機床電氣控制第2版習(xí)題答案習(xí)題答案
- 2024物流與智慧城市建設(shè)合作框架協(xié)議3篇
- 2024版精裝修房屋合同模板:權(quán)益保障與細節(jié)解析
- 2025年度數(shù)據(jù)中心設(shè)備采購及運維服務(wù)合同3篇
- 沈陽城市學(xué)院《飛機載重與平衡》2023-2024學(xué)年第一學(xué)期期末試卷
- 陽泉師范高等??茖W(xué)?!遁啓C化學(xué)》2023-2024學(xué)年第一學(xué)期期末試卷
- 2024庭院房屋產(chǎn)權(quán)轉(zhuǎn)讓合同書樣本3篇
- 內(nèi)蒙古美術(shù)職業(yè)學(xué)院《區(qū)域經(jīng)濟學(xué)實驗》2023-2024學(xué)年第一學(xué)期期末試卷
- 合肥市建筑行業(yè)施工安全生產(chǎn)標(biāo)準(zhǔn)化示范工地評選辦法
- 2025年度航空航天材料研發(fā)與應(yīng)用技術(shù)服務(wù)合同2篇
- AEO貿(mào)易安全培訓(xùn)
- 2025年中國財產(chǎn)險行業(yè)市場深度分析及發(fā)展趨勢預(yù)測報告
- 巨量信息流廣告(初級)營銷師認證考試題及答案
- 銀行會計主管年度工作總結(jié)2024(30篇)
- 上海市12校2025屆高三第一次模擬考試英語試卷含解析
- 重慶市渝中區(qū)2023-2024學(xué)年八年級上學(xué)期期末考試數(shù)學(xué)試題含答案及解析
- 【MOOC】教學(xué)研究的數(shù)據(jù)處理與工具應(yīng)用-愛課程 中國大學(xué)慕課MOOC答案
- 工商企業(yè)管理畢業(yè)論文范文 工商企業(yè)管理5000論文范文
- 《小學(xué)科學(xué)實驗創(chuàng)新》課件
評論
0/150
提交評論