




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
CS1010SLecture8:
ImplementingDataStructures15Oct2014SayingoftheWise"IhearandIforget.IseeandIremember.IdoandIunderstand."
--
Confucius
SomePhilosophyPythonislikechessEasytolearn,hardtomasterLevelsoflearningKnowledgeUnderstandingApplicationSecretRecipeforSuccessinCS1010FCDOINGIT(Gettinghandsdirtyandwritingcode)!LectureTrainingsRecitationTutorialMissionsLotsofOptional
TrainingsPythonyoushouldknowPythonStatements:defreturnlambdaif,elif,elsefor,while,
break,continueimportDataabstractionprimitives:tuplelistBelieveitornot:youalreadyknowmostofthePythonthatyouneedtoknowforCS1010S!!Re-Midtermon
17Oct2014(Fri)
@7pm
I3AuditoriumMake-UpLectureon18Oct2014(Sat)@10am
LT19,SoCToday’sAgendaTheGameofNimMoreWishfulThinkingUnderstandingSchemecodeSimpledatastructuresDesigningDataStructuresMultipleRepresentationsTheGameofNimTwoplayersGameboardconsistsofpilesofcoinsPlayerstaketurnsremovinganynumberofcoinsfromasinglepilePlayerwhotakesthelastcoinwinsLet’sPlay!!HowtoWriteThisGame?KeeptrackofthegamestateSpecifygamerulesFigureoutstrategyGluethemalltogetherLet’sstartwithasimplegamewithtwopilesStartwithGameStateWhatdoweneedtokeeptrackof?Numberofcoinsineachpile!GameStateWishfulthinking:
Assumewehave: defmake_game_state(n,m):
...wherenandmarethenumberofcoinsineachpile.WhatElseDoWeNeed? defsize_of_pile(game_state,p):... wherepisthenumberofthepile defremove_coins_from_pile(game_state,n,p):
... wherepisthenumberofthepileandnisthe
numberofcoinstoremovefrompilep.Let’sstartwiththegame
defplay(game_state,player):display_game_state(game_state)ifis_game_over(game_state):announce_winner(player)elifplayer=="human":play(human_move(game_state),"computer")elifplayer=="computer":play(computer_move(game_state),"human")Whathappensifweevaluate:
play(make_game_state(5,8),"mickey-mouse")TakeCareofErrorCondition
defplay(game_state,player):display_game_state(game_state)ifis_game_over(game_state):announce_winner(player)elifplayer=="human":play(human_move(game_state),"computer")elifplayer=="computer":play(computer_move(game_state),"human")
else:print("playerwasn'thumanorcomputer:",player)
DisplayingGameState
defdisplay_game_state(game_state):print("")print("Pile1:"+str(size_of_pile(game_state,1)))print("Pile2:"+str(size_of_pile(game_state,2)))print("")GameOverCheckingforgameover:
defis_game_over(game_state):returntotal_size(game_state)==0deftotal_size(game_state):returnsize_of_pile(game_state,1)+size_of_pile(game_state,2)Announcingwinner/loser:
defannounce_winner(player):ifplayer=="human":print("Youlose.Betterlucknexttime.")else:print("Youwin.Congratulations.")GettingHumanPlayer’sMovedefhuman_move(game_state):p=prompt("Whichpilewillyouremovefrom?")n=prompt("Howmanycoinsdoyouwanttoremove?")returnremove_coins_from_pile(game_state,int(n),int(p))defprompt(prompt_string):returninput(prompt_string)ArtificialIntelligencedefcomputer_move(game_state):pile=1ifsize_of_pile(game_state,1)>0else2print("Computerremoves1coinfrompile"+str(pile))returnremove_coins_from_pile(game_state,1,pile)Isthisagoodstrategy?GameStatedefmake_game_state(n,m): return(10*n)+mdefsize_of_pile(game_state,pile_number): ifpile_number==1: returngame_state//10 else: returngame_state%10defremove_coins_from_pile(game_state, num_coins,pile_number): ifpile_number==1: returngame_state–10*num_coins else: returngame_state-num_coinsWhatisthelimitationofthisrepresentation?AnotherImplementationdefmake_game_state(n,m):return(n,m)defsize_of_pile(game_state,p):returngame_state[p-1]AnotherImplementationdefremove_coins_from_pile(game_state,num_coins,pile_number):ifpile_number==1:returnmake_game_state(size_of_pile(game_state,1) -num_coins,size_of_pile(game_state,2))else:returnmake_game_state(size_of_pile(game_state,1),size_of_pile(game_state,2)-num_coins)ImprovingNimLetsmodifyourNimgamebyallowing“undo”O(jiān)nlyHumanplayercanundo,notComputerRemoveseffectofthemostrecentmovei.e.undomostrecentcomputerandhumanmoveHuman’sturnagainafterundoHumanenters”0”toindicateundoKeyInsightWeneedadatastructuretorememberthehistoryofgamestatesHistoryofgamestatesBeforeeachhumanmove,addthecurrentgamestatetothehistory.Whenundoing,RemovemostrecentgamestatefromhistoryMakethisthecurrentgamestateDatastructure:StackAstackisadatastructurewiththeLIFOproperty.LastIn,FirstOutItemsareremovedinthereverseorderinwhichtheywereadded.WishfulthinkingagainAssumewehavethefollowing:make_stack():returnsanew,emptystackpush(s,item):addsitemtostackspop(s):removesthemostrecentlyaddeditemfromstacks,andreturnsitis_empty(s):returns#tifsisempty,#fotherwiseStackoperationss=make-stack()pop(s)None:emptystack,nothingtopoppush(s,5)push(s,3)pop(s)3pop(s)5is_empty(s)TrueImplementastackashomeworkChangestoNimgame_stack=make_stack()defhuman_move(game_state):p=prompt("Whichpilewillyouremovefrom?")n=prompt("Howmanycoinsdoyouwanttoremove?")
ifint(p)==0:returnhandle_undo(game_state)else: push(game_stack,game_state)returnremove_coins_from_pile(game_state,int(n),int(p))ChangestoNimdefhandle_undo(game_state):old_state=pop(game_stack)ifold_state:display_game_state(old_state)returnhuman_move(old_state)else:print("Nomorepreviousmoves!")returnhuman_move(game_state)DataStructures:DesignPrinciplesWhendesigningadatastructure,needtospellout:SpecificationImplementationSpecification(contract)Whatdoesitdo?Allowsotherstouseit.ImplementationHowisitrealized?Usersdonotneedtoknowthis.Choiceofimplementation.Nim:Gamestatepiles,coinsineachpilesize,remove-coinMultiplerepresentations possibleSpecificationConceptualdescriptionofdatastructure.Overviewofdatastructure.Stateassumptions,contracts,guarantees.Giveexamples.SpecificationOperations:ConstructorsSelectors(Accessors)PredicatesPrintersExample:ListsSpecs:Alistisacollectionofobjects,inagivenorder.e.g.[],[3,4,1]Example:ListsSpecs:Constructors:Selectors:Predicates:Printer:list(),[][]type,inprintSets:SpecsAsetisanunorderedcollectionofobjects(numbers,inourexample)without
duplicates.e.g.{3,1,2},{1,2,3}arethesamee.g.empty_set
isemptysete.g.{3,3,1,2}isnotvalid!Sets:SpecsConstructors:make_set,adjoin_set,union_set,intersection_setSelectors:Predicates:is_element_of_set,is_empty_setPrinters:print_setSets:ContractForanysetsS,T,andanyobjectx>>>is_element_of_set(x,adjoin_set(x,S))TrueAdjoininganobjecttoasetproducesasetthatcontainstheobject.Sets:Contract>>>is_element_of_set(x,union_set(S,T))
isequalto
>>>is_element_of_set(x,S)oris_element_of_set(x,T)Theelementsof(unionST)aretheelementsthatareinSorinT.>>>is_element_of_set(x,empty_set)Noobjectisanelementoftheemptyset.etc…ImplementationChoosearepresentationUsuallytherearechoices,e.g.lists,treesDifferentchoicesaffecttime/spacecomplexity.Theremaybecertainconstraintsontherepresentation.Theseshouldexplicitlystated.e.g.inrationalnumberpackage,denom≠0ImplementationImplementconstructors,selectors,predicates,printers,usingyourselectedrepresentation.Makesureyousatisfyallcontractsstatedinspecification!Sets:Implementation#1Representation:unorderedlistEmptysetrepresentedbyemptylist.Setrepresentedbyalistoftheobjects.MusttakecaretoavoidduplicatesSets:Implementation#1Constructors:defmake_set():
’’’returnsanew,emptyset’’’
return[]Predicates:defis_empty_set(s):returnnotsSets:Implementation#1Predicates:defis_element_of_set(x,s):ifis_empty_set(s):returnFalseforeins:ife==x:returnTruereturnFalseTimecomplexity:O(n
),nissizeofsetSets:Implementation#1Constructors:defadjoin_set(x,s): ifnotis_element_of_set(x,s): s.append(x)#don’taddifalreadyin returnsTimecomplexity:O(n)Sets:Implementation#1Constructors:defintersection_set(s1,s2): <...........> return<.....>
leftasanexercise (Questionoftheday!)
Sets:Implementation#2Representation:orderedlistEmptysetrepresentedbyemptylist.Musttakecaretoavoidduplicates.Butnowobjectsaresorted.WHYWOULDWEWANTTODOTHIS?Sets:Implementation#2Note:specsdoesnotrequirethis,butwecanimposeadditionalconstraintsinimplementation.Butthisisonlypossibleiftheobjectsarecomparable,i.e.conceptof“greater_than”or“l(fā)ess_than”.e.g.numbers:<e.g.strings,symbols:lexicographicalorder(alphabetical)Notcolors:red,blue,greenSets:Implementation#2Constructors:defmake_set(): return[]#asbeforePredicates:defis_empty_set(s):returnnots#asbeforeSets:Implementation#2Predicates:defis_element_of_set(x,s):ifis_empty_set(s):returnFalseforeins:ife==x:returnTrueelife>x:returnFalsereturnFalseTimecomplexity:O(n),butfasterthanprevious!IntersectionSet1:(1348)Set2:(145689)
so1inintersection,moveset1,set2cursorforwardSet1:(348)Set2:(45689)
3<4,3notinintersection,forwardset1cursoronlyIntersectionSet1:(48)Set2:(45689)
so4inintersection,forwardset1,set2cursorSet1:(8)Set2:(5689)
8>5,5notinintersection,forwardset2cursoronlyIntersectionSet1:(8)Set2:(689)
8>6,6notinintersection,forwardset2cursorSet1:(8)Set2:(89)
so8inintersection,forwardset1,set2cursorIntersectionSet1:()Set2:(9)
set1empty,return()appendeverythingtogether:(148)Sets:Implementation#2Constructors:defintersection_set(s1,s2):ifis_empty_set(s1)oris_empty_set(s2):return[]result=[]i,j=0,0whilei<len(s1)andj<len(s2):ifs1[i]==s2[j]: result.append(s1[i])i=i+1 j=j+1 elifx1<x2: i=i+1
Sets:Implementation#2else:j=j+1returnresultTimecomplexity:O(n),fasterthanprevious!Sets:Implementation#3Representation:binarytreeEmptysetrepresentedbyemptytree.Musttakecaretoavoidduplicates.Objectsaresorted.Sets:Implementation#3Eachnodestores1object.Leftsubtreecontainsobjectssmallerthanthis.Rightsubtreecontainsobjectsgreaterthanthis.Sets:Implementation#3Threetreesrepresentingtheset{1,3,5,7,9,11}793511137195115937111Sets:Implementation#3Treeoperators:defmake_tree(entry,left,right): return(entry,left,right)defentry(tree): returntree[0]defleft_branch(tree): returntree[1]defright_branch(tree): returntree[2]Sets:Implementation#3Predicates:defis_element_of_set(x,s): ifis_empty_set(s): returnFalse elifx==entry(s): returnTrue elifx<entry(s): returnis_element_of_set(x,left_branch(s)) else: returnis_element_of_set(x,right_branch(s))Timecomplexity:O(logn)Sets:Implementation#3Adjoin:defadjoin_set(x,s): ifis_empty_set(s): returnmake_tree(x,[],[]) elifx==entry(s): returns elifx<entry(s): returnmake_tree(entry(s), adjoin_set(x,left_branch(s)), right_branch(s)) else: returnmake_tree(entry(s),left_branch(s), adjoin_set(x,right_branch(s))BalancingtreesOperationisO(logn)assumingthattreeisbalanced.Buttheycaneunbalancedafterseveraloperations.Unbalancedtreesbreakthelogncomplexity.Onesolution:defineafunctiontorestorebalance.Calliteverysooften.5791113QuestionoftheDayHowdoweconvertanunbalancedbinarytreeintoabalancedtree?Writeafunctionbalance_tree
thatwilltakeabinarytreeandreturnabalancedtree(orasbalancedasyoucanmakeit)MultiplerepresentationsYouhaveseenthatforcompounddata,multiplerepresentationsarepossible:e.g.setsas:Unorderedlists,w/oduplicatesOrderedlists,w/oduplicatesBinarytrees,w/oduplicatesMultiplerepresentationsEachrepresentationhasitspros/cons:Typically,someoperationsaremoreefficient,somearelessefficient.“Best”representationmaydependonhowtheobjectisused.Typicallyinlargesoftwareprojects,multiplerepresentationsco-exist.Why?ManypossiblereasonsBecauselargeprojectshavelonglifetime,andprojectrequirementschangeovertime.Becausenosinglerepresentationissuitableforeverypurpose.Becauseprogrammersworkindependentlyanddeveloptheirownrepresentationsforthesamething.MultiplerepresentationsTherefore,youmustlearntomanagedifferentco-existingrepresentations.Whataretheissues?Whatstrategiesareavailable?Whatarethepros/cons?Complex-arithmeticpackageRecall:complexnumbers 3+4i,i=√-1 x+iy ,x:realpart,y:imaginarypartTheaboveisrectangularform.Thereisalsopolar
form:z=x+iy=re
iAr:magnitudeA:angleAbstractionbarrierRectangularrepresentationPolarrepresentationComplex-arithmeticpackageProgramsthatusecomplexnumbersplex,plex,plex,plexBenhasprovidedthisAlyssahasprovidedthisYouwanttobuildthisArithmeticpackageSimilartorationalnumberpackage(Lecture7)Addition:z=z1+z2
real_part(z)=real_part(z1)+real_part(z2) imag_
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025-2030年中國(guó)除塵設(shè)備產(chǎn)業(yè)運(yùn)營(yíng)狀況與發(fā)展?jié)摿Ψ治鰣?bào)告
- 2025-2030年中國(guó)鉛白市場(chǎng)發(fā)展現(xiàn)狀及前景趨勢(shì)分析報(bào)告
- 2025-2030年中國(guó)鎢鐵行業(yè)發(fā)展現(xiàn)狀及前景趨勢(shì)分析報(bào)告
- 2025-2030年中國(guó)轎車(chē)懸架彈簧轎行業(yè)發(fā)展?fàn)顩r及前景趨勢(shì)分析報(bào)告
- 2025-2030年中國(guó)葡萄糖酸鈣市場(chǎng)競(jìng)爭(zhēng)狀況及投資趨勢(shì)分析報(bào)告
- 2025-2030年中國(guó)色選機(jī)市場(chǎng)競(jìng)爭(zhēng)格局及發(fā)展趨勢(shì)分析報(bào)告
- 2025-2030年中國(guó)紡織品直噴墨水行業(yè)發(fā)展趨勢(shì)與十三五規(guī)劃研究報(bào)告
- 2025-2030年中國(guó)立磨市場(chǎng)運(yùn)行態(tài)勢(shì)及投資戰(zhàn)略研究報(bào)告
- 2025-2030年中國(guó)硫磺回收市場(chǎng)運(yùn)行狀況及發(fā)展趨勢(shì)預(yù)測(cè)報(bào)告
- 2025-2030年中國(guó)石蠟行業(yè)市場(chǎng)運(yùn)行狀況及發(fā)展策略分析報(bào)告
- 亞專(zhuān)科護(hù)理建設(shè)思路
- 500-3000總噸船舶大副培訓(xùn)大綱(2021版)
- 公務(wù)員2019年國(guó)考《申論》真題及答案(地市級(jí))
- 輪系獲獎(jiǎng)?wù)n件
- 小學(xué)三年級(jí)下冊(cè)體育教案
- 【《蘇泊爾公司存貨管理的優(yōu)化建議分析》13000字論文】
- 2024年車(chē)載SoC發(fā)展趨勢(shì)及TOP10分析報(bào)告-2024-09-零部件
- 伽馬數(shù)據(jù):2024年中國(guó)游戲產(chǎn)業(yè)趨勢(shì)及潛力分析報(bào)告
- 北師大版八年級(jí)生物下冊(cè)全冊(cè)課件(2024年春季版)
- 高一英語(yǔ)完形填空專(zhuān)項(xiàng)訓(xùn)練100(附答案)及解析
- 機(jī)房基礎(chǔ)設(shè)施運(yùn)行維護(hù)管理標(biāo)準(zhǔn)規(guī)范
評(píng)論
0/150
提交評(píng)論