CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… ·...

13
CS1 Lecture 35 Apr. 14, 2017 HW6 scores have been posted HW 8 due Wed. Q2 based on today’s material (will be posted by this aIernoon) Exam 2: April 20, 6:30-8:00pm Main topics: dicPonaries (Ch 11), classes and objects (Ch 15-18), algorithm analysis (Ch 21), sorPng and searching, graphs randomizaPon. Details on Mon. and Wed.

Transcript of CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… ·...

Page 1: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

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.

Page 2: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

AninteresPngvideo hUps://strangeparts.com/how-i-made-my-own-iphone-in-china/

Page 3: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

Today

LastPme

•  SomeproblemsinvolvingrandomizaPonandsimulaPon

•  ReviewedgraphrepresentaPonandbfstraversal

•  DiscussHW8wordladderproblem•  Shortdepth-firstsearchoverview

Page 4: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

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!)

Page 5: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

•  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

Page 6: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

Again-modifyingNodeclassandbfsforwordLadder

1.addparentpropertyandgetParentandsetParentmethodstoNodeclass2.modifybfs:Markallnodes‘unseen’Setallnodes’parentstoNoneMarkstartnode‘seen’andputitonqueueUnPlqueueemptydo:•  Removethefrontnodeofthequeueandcallitthecurrent

node•  Considereachneighborofthecurrentnode.Ifitsstatusis

‘unseen’,markas‘seen’,setitsparenttocurrentnode,andputitonthequeue.

•  Markthecurrentnode‘processed’

Thisisverysimilartowhatyoudidwithdistanceindisc.secPon

Page 7: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

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”

Page 8: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

MontyHallproblem

– M.vosSavant(whosecolumngeneratedhugepublicawareness)quotespsychologistM.PiaUelli-Palmarini:"...nootherstaPsPcalpuzzlecomessoclosetofoolingallthepeopleallthePme.”HerbransonandSchroeder:Pigeonsrepeatedlyexposedtotheproblemshowthattheyrapidlylearnalwaystodotherightthing,unlikehumans.J

– DemonstratesimulaPonusingrandomizaPontohelp“see”thatswitchingistherightthingtodo.montyhall.py

Page 9: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

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

Page 10: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

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

Page 11: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

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

Page 12: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

AnproblemtothinkaboutforfunYouwanttosellyourphone.Alargelineofpeopleassemblesseekingtobuyit.Eachhasarandompriceoffer(bid)inmind.YouwanttomaximizepriceBUTyoumustconsiderthebidsONEATATIME,intheorderreceived,andREJECTORACCEPTEACHONEIMMEDIATELY.Istherearestrategythatcanmakeitlikelyyougetagoodprice?E.g.“alwaystakefirstbid”–chanceofge|ngbestpriceisthen1/n.Notsogood….

Page 13: CS1 Lecture 35 Apr. 14, 2017homepage.divms.uiowa.edu/~cremer/courses/cs1210-s17/etc/cs1210s… · – order in which nodes are finished/processed: • dist 0 scoff set parent to

NextPmeOneortwomorerandomizaPonexamples.E.g.calculaPngpiviarandomizaPon:hUps://learntofish.wordpress.com/2010/10/13/calculaPng-pi-with-the-monte-carlo-method/IntroducPontographicaluserinterface(GUI)programminginPython