大一下-数算第一次翻译psads-python_第1页
大一下-数算第一次翻译psads-python_第2页
大一下-数算第一次翻译psads-python_第3页
大一下-数算第一次翻译psads-python_第4页
大一下-数算第一次翻译psads-python_第5页
免费预览已结束,剩余158页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

(Python引 Python入 算法分 “大O”表示 列表 字典 栈 抽象数据类型 用Python实现 抽象数据类型 在Python中实现 Python实 讨 抽象数据类型 在Python中实现 抽象数据类型无序列表Unordered 递归 4.4.1.斯基三角形Sierpinski 散 术语 定 二叉堆BinaryHeap实现的优先队 建立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.内建原子数据类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内建集合数据类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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论