Post on 06-Aug-2020
CS1Lecture35 Apr.14,2017• HW6scoreshavebeenposted• HW8dueWed.
– Q2basedontoday’smaterial(willbepostedbythisaIernoon)
• Exam2:April20,6:30-8:00pm
• Maintopics:dicPonaries(Ch11),classesandobjects(Ch15-18),algorithmanalysis(Ch21),sorPngandsearching,graphsrandomizaPon.DetailsonMon.andWed.
AninteresPngvideo hUps://strangeparts.com/how-i-made-my-own-iphone-in-china/
Today
LastPme
• SomeproblemsinvolvingrandomizaPonandsimulaPon
• ReviewedgraphrepresentaPonandbfstraversal
• DiscussHW8wordladderproblem• Shortdepth-firstsearchoverview
HW8Q1WordLadderproblemSeveralparts,nonecomplicated.(AGAIN:Implementandtestparts–don’tjustwriteallthecodeatonceandhopeitworks!)
1. Readwordlistandcreategraph• Onenodeperword• EdgebetweeneachpairofwordsdifferingbyoneleUer
2. Executebreadth-firstsearchstarPngfromstartword’snode.3. “extract”ladderfromgraph(aIerbfs)byfollowingaparentpath(youwilladd‘parent’
propertytoNodeclassandsetduringbfs)fromendword’snodebacktostartnode4. InteracPvelooprequesPnginputfromuser:requesttwowords,callfindLadder(whichshould
returnarepresentaPonoftheladder),printresultnicely
wordladderStart.py(seeHW8assignment)hasstubsforallthefuncPonsyouneed.NOTES:• it’sokaytousesimpleO(n^2)processtocreatethegraph
– Ifyouareinterested,thereisafasterway:hUp://interacPvepython.org/courselib/staPc/pythonds/Graphs/BuildingtheWordLadderGraph.html
• CreateaPnywordfiletoteston.Choosethewords,drawthegraphbyhand,andcheckprogram’sresults.Seeexampleonnextslide.
• findWordLaddershoulddoboth:1. bfs–modifiedtokeeptrackof‘parent’.Whenaneighbornodeismarked‘seen’,setparentto
currentnode.Thisissimilartowhatyoudoindisc.secPonthisweek!2. laddercanbeconstructed/printedbyfollowingparentpathfromendwordtostartword(NOTE:withinteracPvelooprepeatedlyaskingfortwonewwords,aretherecaseswherestep1,thebfs,offindWordLadderisnotnecessary?Don’tworryaboutthis–it’snoproblemtoalwaysdothebfs.It’sfast!)
• Breadthfirstsearchfrom‘scoff’:– orderinwhichnodesarefinished/processed:
• dist0scoff setparenttoNone• dist1scuff setparentto‘scoff’(Nodefor‘scoff’)• dist2snuff,stuff setparentofeachto‘scuff’• dist3sniff(firstseenfrom‘snuff’)setparantto‘snuff’• dist3sPff,staff(seenfrom‘stuff’)setparentofeachto‘stuff’• dist4skiff setparentto‘sPff’
• extractWordLadder(startNode,endNode)– canuseasimpleloop:
• IniPalizevariable,e.g.currentNode,toendNode whatisloop• AddcurrentNodetoaresultlist stopping• UpdatecurrentNodewithcurrentNode’sparent condiPon?
Parentproperty,BFS,andextractWordLadder
Again-modifyingNodeclassandbfsforwordLadder
1.addparentpropertyandgetParentandsetParentmethodstoNodeclass2.modifybfs:Markallnodes‘unseen’Setallnodes’parentstoNoneMarkstartnode‘seen’andputitonqueueUnPlqueueemptydo:• Removethefrontnodeofthequeueandcallitthecurrent
node• Considereachneighborofthecurrentnode.Ifitsstatusis
‘unseen’,markas‘seen’,setitsparenttocurrentnode,andputitonthequeue.
• Markthecurrentnode‘processed’
Thisisverysimilartowhatyoudidwithdistanceindisc.secPon
Monty Hall problem http://en.wikipedia.org/wiki/Monty_Hall_problem
Supposeyou'reonagameshow,andyou'regiventhechoiceofthreedoors:Behindonedoorisacar;behindtheothers,goats.Youpickadoor,sayNo.1,andthehost,whoknowswhat'sbehindthedoors,opensanotherdoor,sayNo.3,whichhasagoat.Hethensaystoyou,"DoyouwanttopickdoorNo.2?"Isittoyouradvantagetoswitchyourchoice?
-Parademagazine,1990,MarilynvosSavant’s“AskMarilyncolumn”
MontyHallproblem
– M.vosSavant(whosecolumngeneratedhugepublicawareness)quotespsychologistM.PiaUelli-Palmarini:"...nootherstaPsPcalpuzzlecomessoclosetofoolingallthepeopleallthePme.”HerbransonandSchroeder:Pigeonsrepeatedlyexposedtotheproblemshowthattheyrapidlylearnalwaystodotherightthing,unlikehumans.J
– DemonstratesimulaPonusingrandomizaPontohelp“see”thatswitchingistherightthingtodo.montyhall.py
AliUleMonteCarlosimulaPonRoughlyspeaking,MonteCarlosimulaPonisafancynameforusingrepeatedrandomsamplingofaproblemspacetodetermineresultslec35coins.pyisaverysimpleMonteCarlosimulaPonofcoinflipping.• doNCoinFlips(numFlips):returnnumberofheadsandnumberoftails
resulPngfromspecifiednumberofflips• doCoinFlipTrials(numTrials,numCoins):doing*one*setofflipsisnot
usuallyagoodwaytodoanexperiment.BeUertodoseveral“trials”flippingthesamenumberofcoins.E.gflip100coins10Pmes
Compute,print,andreturnstaPsPcalinfo:– averagehead/tailraPo(averagedoverthesetoftrials)– stddeviaPonofhead/tailraPos
• doCoinFlipExperiment(minCoins,maxCoins,factor)– collectdoCoinFlipTrialsdatafordifferentnumbersofcoins,sowecanseetrend
ofstaPsPcsasnumberofflipsgrows:• minNum,minNum*factor,minNum*factor*factor,…
• plotResults– usepylabtocreategraphsofstatsgatheredbydoCoinFlipExperiment
HW8Q2Supposeweflip15coinsandtheresultisH,T,T,H,H,H,T,H,H,T,H,T,T,T,TThelengthofthelongestconsecuPve“run”ofheadsis3.Ifyouflip100coins,whatdoexpectwillbethelengthofthelongestconsecuPvestringofheads?Howcanwefigurethisout?Flip100coinsonce?BeUer:flip100coinsseveralPmesandtakeaverage.Howabout200coins?1000coins?Asnumberofcoinsgrows,howdoexpectlongrunlengthgrow? HW8Q2:modifylec35coins.py totrytoanswerthisproblem
Noreasontobelieveresultisclosetoexpectedvalueifwedoitagain
UsingrandomizaPontomixup(shuffle)alistofnumbers
defmixup(L):newL=L[:]length=len(L)foriinrange(length):newIndex=random.randint(0,length-1)newL[newIndex],newL[i]=newL[i],newL[newIndex]return(newL)
• Whatdoyouthink?• Testonafewlists. mixupB.py
>>>mixup([1,2,3,4,5])[1,3,4,5,2]
• RuntestMixup(100000).Whatdoyouexpectasresult?• Hmm…• See:hUp://blog.codinghorror.com/the-danger-of-naivete/and
hUps://www.cigital.com/papers/download/developer_gambling.php
AnproblemtothinkaboutforfunYouwanttosellyourphone.Alargelineofpeopleassemblesseekingtobuyit.Eachhasarandompriceoffer(bid)inmind.YouwanttomaximizepriceBUTyoumustconsiderthebidsONEATATIME,intheorderreceived,andREJECTORACCEPTEACHONEIMMEDIATELY.Istherearestrategythatcanmakeitlikelyyougetagoodprice?E.g.“alwaystakefirstbid”–chanceofge|ngbestpriceisthen1/n.Notsogood….
NextPmeOneortwomorerandomizaPonexamples.E.g.calculaPngpiviarandomizaPon:hUps://learntofish.wordpress.com/2010/10/13/calculaPng-pi-with-the-monte-carlo-method/IntroducPontographicaluserinterface(GUI)programminginPython