Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Call Pattern of Recursive Fib() Function
11/18/16 Page 35
Efficiency of Recursion • Thefunc)ontakessolongbecauseitcomputesthesamevaluesover
andover.
• Computa)onoffib(6)callsfib(3)three)mes.
• Imitatethepencil-and-paperprocesstoavoidcompu)ngthevaluesmorethanonce.
11/18/16 Page 36
Efficiency of Recursion • Occasionally,arecursivesolu)onrunsmuchslowerthanitsitera)vecounterpart.
• Inmostcases,therecursivesolu)onisonlyslightlyslower.
• Theitera)veisPalindrome()performsonlyslightlybe@erthanrecursivesolu)on.
• Eachrecursivefunc.oncalltakesacertainamountofprocessor.me
11/18/16 Page 37
Loopfib.py(1)
Page 38 11/18/16
Loopfib.py(2)
Page 39 11/18/16
Memoized Fibonacci
11/18/16 Page 40
Efficiency of Recursion • Smartcompilerscanavoidrecursivefunc)oncallsiftheyfollowsimplepa@erns.
• Mostcompilersdon’tdothat
• Inmanycases,arecursivesolu)oniseasiertounderstandandimplementcorrectlythananitera)vesolu)on.
• ‘Toiterateishuman,torecursedivine.’-L.PeterDeutsch
Page 41 11/18/16
Iterative IsPalindrome()Function
Page 42
defisPalindrome(text):start=0end=len(text)-1whilestart<end:first=text[start].lower()last=text[end].lower()iffirst.isalpha()andlast.isalpha():#Bothareletters.iffirst==last:start=start+1end=end-1else:returnFalseifnotlast.isalpha()end=end-1
11/18/16
11.5 Permutations • Designaclassthatwilllistallpermuta)onsofstring,whereapermuta)onisarearrangementofthele@ers
• Thestring"eat"hassixpermuta)ons:• "eat"• "eta"• "aet"• "ate"• "tea"• "tae"
11/18/16 Page 43
Generate All Permutations (1) • Generateallpermuta)onsthatstartwith'e',then'a',then't'
• Thestring"eat"hassixpermuta)ons:• "eat"• "eta"• "aet"• "ate"• "tea"• "tae"
11/18/16 Page 44
Generate All Permutations (2) • Generateallpermuta)onsthatstartwith'e',then'a',then't'
• Togeneratepermuta)onsstar)ngwith'e',weneedtofindallpermuta)onsof"at"
• Thisisthesameproblemwithsimplerinputs
• Userecursion
11/18/16 Page 45
Implementing Permutations() Function
• Loopthroughallposi)onsinthewordtobepermuted
• Foreachofthem,computetheshorterwordobtainedbyremovingtheithle@er:
11/18/16 Page 46
shorter=word[:i]+word[i+1:]
shorterPermutations=permutations(shorter)
• Computethepermuta)onsoftheshorterword:
Implementing Permutations() Function • Addtheremovedle@ertothefrontofallpermuta)onsoftheshorterword:
11/18/16 Page 47
forsinshorterPermutations:result.append(word[i]+s)
• Specialcaseforthesimpleststring,theemptystring,whichhasasinglepermuta)on-itself
Permutations.py (1)
Page 48 11/18/16
Permutations.py (2)
Page 49 11/18/16
Backtracking • Backtrackingexaminespar)alsolu)ons,abandoningunsuitableonesandreturningtoconsiderothercandidates
• Canbeusedto• solvecrosswordpuzzles
• escapefrommazes
• findsolu)onstosystemsthatareconstrainedbyrules
11/18/16 Page 50
Backtracking Characteristic Properties 1. Aproceduretoexamineapar)alsolu)onanddeterminewhether
to:
I. acceptitasanactualsolu)onor,
II. abandonit(becauseiteitherviolatessomerulesorcanneverleadtoavalidsolu)on)
2. Aproceduretoextendapar)alsolu)on,genera)ngoneormoresolu)onsthatcomeclosertothegoal
11/18/16 Page 51
Recursive Backtracking Algorithm Solve(partialSolution)
Examine(partialSolution).
Ifaccepted
AddpartialSolutiontothelistofsolutions.
Elseifnotabandoned
Foreachpinextend(partialSolution)
Solve(p)
11/18/16 Page 52
Eight Queens Problem • Problem:posi)oneightqueensonachessboardsothatnoneofthema@acksanotheraccordingtotherulesofchess
• Asolu)on:
11/18/16 Page 53
Eight Queens Problem • Easytoexamineapar)alsolu)on:
• Iftwoqueensa@ackoneanother,rejectit• Otherwise,ifithaseightqueens,acceptit• Otherwise,con)nue
• Easytoextendapar)alsolu)on:• Addanotherqueenonanemptysquare
• Systema)cextensions:
• Placefirstqueenonrow1• Placethenextonrow2• Etc.
11/18/16 Page 54
Function: Examine()
11/18/16 Page 55
defexamine(partialSolution):foriinrange(0,len(partialSolution)):forjinrange(i+1,len(partialSolution)):ifattacks(partialSolution[i],partialSolution[j]):returnABANDONiflen(partialSolution)==NQUEENS:returnACCEPTelse:returnCONTINUE
Function: Extend()
11/18/16 Page 56
defextend(partialSolution):results=[]row=len(partialSolution)+1forcolumnin"abcdefgh":newSolution=list(partialSolution)newSolution.append(column+str(row))results.append(newSolution)returnresults
Diagonal Attack • Todeterminewhethertwoqueensa@ackeachotherdiagonally:
• Checkwhetherslopeis±1
(row2–row1)/(column2–column1)=±1
row2–row1=±(column2–column1)
row2–row1|=|column2–column1|
11/18/16 Page 57
Backtracking in the Four Queens Problem (1)
11/18/16 Page 58
Backtracking in the Four Queens Problem (2)
• Star)ngwithablankboard,fourpar)alsolu)onswithaqueeninrow1
• Whenthequeenisincolumn1,fourpar)alsolu)onswithaqueeninrow2
• Twoareabandonedimmediately
• Othertwoleadtopar)alsolu)onswiththreequeensand,allbutoneofwhichareabandoned
• Onepar)alsolu)onisextendedtofourqueens,butallofthoseareabandonedaswell
11/18/16 Page 59
Queens.py
Page 60 11/18/16
Queens.py
Page 61 11/18/16
Queens.py
Page 62 11/18/16
11.7 Mutual Recursion • Problem:Computethevalueofarithme)cexpressionssuchas:
3 + 4 * 5 (3 + 4) * 5 1 - (2 - (3 - (4 - 5)))
• Compu)ngtheexpressioniscomplicated
• *and/ bindmorestronglythan+ and–
• Parenthesescanbeusedtogroupsub-expressions
11/18/16 Page 63
Syntax Diagrams for Evaluating an Expression
11/18/16 Page 64
Mutual Recursion • Anexpressioncanbebrokendownintoasequenceofterms,separatedby+or–
• Eachtermisbrokendownintoasequenceoffactors,separatedby*or/
• Eachfactoriseitheraparenthesizedexpressionoranumber
• Thesyntaxtreesrepresentwhichopera)onsshouldbecarriedoutfirst
11/18/16 Page 65
Syntax Trees for Two Expressions
11/18/16 Page 66
Mutual Recursion • Inamutualrecursion,asetofcoopera)ngfunc)onscallseachotherrepeatedly
• Tocomputethevalueofanexpression,implement3func)onsthatcalleachotherrecursively:
• expression()
• term()
• factor()
11/18/16 Page 67
Function: Expression()
11/18/16 Page 68
defexpression(tokens):value=term(tokens)done=Falsewhilenotdoneandlen(tokens)>0:next=tokens[0]ifnext=="+"ornext=="-":tokens.pop(0)#Discard"+"or"-"value2=term(tokens)ifnext=="+":value=value+value2else:value=value-value2else:done=Truereturnvalue
Function: Term()• Theterm()func)oncallsfactor()inthesameway,mul)plyingordividingthefactorvalues
11/18/16 Page 69
defterm(tokens):value=factor(tokens)done=Falsewhilenotdoneandlen(tokens)>0:next=tokens[0]ifnext=="*"ornext=="/":tokens.pop(0)value2=factor(tokens)ifnext=="*":value=value*value2else:value=value/value2else:done=Truereturnvalue
Function: Factor()
11/18/16 Page 70
deffactor(tokens):next=tokens.pop(0)ifnext=="(":value=expression(tokens)tokens.pop(0)#Discard")"else:value=nextreturnvalue
Trace (3+4)*5
11/18/16 Page 71
To see the mutual recursion clearly, trace through the expression (3+4)*5:
• expression()callsterm()
• term()callsfactor()
• factor()consumesthe(input
• factor()callsexpression()
• expression()returnseventuallywiththevalueof7,havingconsumed3+4.Thisistherecursivecall.
• factor()consumesthe)input
• factor()returns7
• term()consumestheinputs*and5andreturns35
• expression()returns35
Evaluator.py (1)
11/18/16 Page 72
Evaluator.py
11/18/16 Page 73
Evaluator.py
Page 74 11/18/16
Evaluator.py
Page 75 11/18/16
Summary • Understandthecontrolflowinarecursivecomputa)on.
• Arecursivecomputa)onsolvesaproblembyusingthesolu)ontothesameproblemwithsimplerinputs.
• Forarecursiontoterminate,theremustbespecialcasesforthesimplestvalues.
• Designarecursivesolu)ontoaproblem.
11/18/16 Page 76
Summary • Iden)fyrecursivehelperfunc)onsforsolvingaproblem.
• Some)mesitiseasiertofindarecursivesolu)onifyoumakeaslightchangetotheoriginalproblem.
• Contrasttheefficiencyofrecursiveandnon-recursivealgorithms.• Occasionally,arecursivesolu)onrunsmuchslowerthanitsitera)vecounterpart.However,inmostcases,therecursivesolu)onisonlyslightlyslower.
• Inmanycases,arecursivesolu)oniseasiertounderstandandimplementcorrectlythananitera)vesolu)on.
11/18/16 Page 77
Summary • Reviewacomplexrecursionexamplethatcannotbesolvedwithasimpleloop.• Thepermuta)onsofastringcanbeobtainedmorenaturallythroughrecursionthanwithaloop.
• Usebacktrackingtosolveproblemsthatrequiretryingoutmul)plepaths.• Backtrackingexaminespar)alsolu)ons,abandoningunsuitableonesandreturningtoconsiderothercandidates.
11/18/16 Page 78
Summary • Recognizethephenomenonofmutualrecursioninanexpressionevaluator.• Inamutualrecursion,coopera)ngfunc)onsormethodscalleachotherrepeatedly.
11/18/16 Page 79