Top Banner
Call Pattern of Recursive Fib() Function 11/18/16 Page 35
45

Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Aug 13, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Call Pattern of Recursive Fib() Function

11/18/16 Page 35

Page 2: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Efficiency of Recursion •  Thefunc)ontakessolongbecauseitcomputesthesamevaluesover

andover.

•  Computa)onoffib(6)callsfib(3)three)mes.

•  Imitatethepencil-and-paperprocesstoavoidcompu)ngthevaluesmorethanonce.

11/18/16 Page 36

Page 3: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Efficiency of Recursion •  Occasionally,arecursivesolu)onrunsmuchslowerthanitsitera)vecounterpart.

•  Inmostcases,therecursivesolu)onisonlyslightlyslower.

•  Theitera)veisPalindrome()performsonlyslightlybe@erthanrecursivesolu)on.

•  Eachrecursivefunc.oncalltakesacertainamountofprocessor.me

11/18/16 Page 37

Page 4: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Loopfib.py(1)

Page 38 11/18/16

Page 5: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Loopfib.py(2)

Page 39 11/18/16

Page 6: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Memoized Fibonacci

11/18/16 Page 40

Page 7: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Efficiency of Recursion •  Smartcompilerscanavoidrecursivefunc)oncallsiftheyfollowsimplepa@erns.

•  Mostcompilersdon’tdothat

•  Inmanycases,arecursivesolu)oniseasiertounderstandandimplementcorrectlythananitera)vesolu)on.

•  ‘Toiterateishuman,torecursedivine.’-L.PeterDeutsch

Page 41 11/18/16

Page 8: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 9: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

11.5 Permutations •  Designaclassthatwilllistallpermuta)onsofstring,whereapermuta)onisarearrangementofthele@ers

•  Thestring"eat"hassixpermuta)ons:•  "eat"•  "eta"•  "aet"•  "ate"•  "tea"•  "tae"

11/18/16 Page 43

Page 10: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 11: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 12: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Implementing Permutations() Function

•  Loopthroughallposi)onsinthewordtobepermuted

•  Foreachofthem,computetheshorterwordobtainedbyremovingtheithle@er:

11/18/16 Page 46

shorter=word[:i]+word[i+1:]

shorterPermutations=permutations(shorter)

•  Computethepermuta)onsoftheshorterword:

Page 13: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Implementing Permutations() Function •  Addtheremovedle@ertothefrontofallpermuta)onsoftheshorterword:

11/18/16 Page 47

forsinshorterPermutations:result.append(word[i]+s)

•  Specialcaseforthesimpleststring,theemptystring,whichhasasinglepermuta)on-itself

Page 14: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Permutations.py (1)

Page 48 11/18/16

Page 15: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Permutations.py (2)

Page 49 11/18/16

Page 16: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Backtracking •  Backtrackingexaminespar)alsolu)ons,abandoningunsuitableonesandreturningtoconsiderothercandidates

•  Canbeusedto•  solvecrosswordpuzzles

•  escapefrommazes

•  findsolu)onstosystemsthatareconstrainedbyrules

11/18/16 Page 50

Page 17: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 18: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Recursive Backtracking Algorithm Solve(partialSolution)

Examine(partialSolution).

Ifaccepted

AddpartialSolutiontothelistofsolutions.

Elseifnotabandoned

Foreachpinextend(partialSolution)

Solve(p)

11/18/16 Page 52

Page 19: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Eight Queens Problem •  Problem:posi)oneightqueensonachessboardsothatnoneofthema@acksanotheraccordingtotherulesofchess

•  Asolu)on:

11/18/16 Page 53

Page 20: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 21: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 22: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 23: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Diagonal Attack •  Todeterminewhethertwoqueensa@ackeachotherdiagonally:

•  Checkwhetherslopeis±1

(row2–row1)/(column2–column1)=±1

row2–row1=±(column2–column1)

row2–row1|=|column2–column1|

11/18/16 Page 57

Page 24: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Backtracking in the Four Queens Problem (1)

11/18/16 Page 58

Page 25: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 26: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Queens.py

Page 60 11/18/16

Page 27: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Queens.py

Page 61 11/18/16

Page 28: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Queens.py

Page 62 11/18/16

Page 29: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 30: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Syntax Diagrams for Evaluating an Expression

11/18/16 Page 64

Page 31: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Mutual Recursion •  Anexpressioncanbebrokendownintoasequenceofterms,separatedby+or–

•  Eachtermisbrokendownintoasequenceoffactors,separatedby*or/

•  Eachfactoriseitheraparenthesizedexpressionoranumber

•  Thesyntaxtreesrepresentwhichopera)onsshouldbecarriedoutfirst

11/18/16 Page 65

Page 32: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Syntax Trees for Two Expressions

11/18/16 Page 66

Page 33: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Mutual Recursion •  Inamutualrecursion,asetofcoopera)ngfunc)onscallseachotherrepeatedly

•  Tocomputethevalueofanexpression,implement3func)onsthatcalleachotherrecursively:

•  expression()

•  term()

•  factor()

11/18/16 Page 67

Page 34: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 35: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 36: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Function: Factor()

11/18/16 Page 70

deffactor(tokens):next=tokens.pop(0)ifnext=="(":value=expression(tokens)tokens.pop(0)#Discard")"else:value=nextreturnvalue

Page 37: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 38: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Evaluator.py (1)

11/18/16 Page 72

Page 39: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Evaluator.py

11/18/16 Page 73

Page 40: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Evaluator.py

Page 74 11/18/16

Page 41: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Evaluator.py

Page 75 11/18/16

Page 42: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Summary •  Understandthecontrolflowinarecursivecomputa)on.

•  Arecursivecomputa)onsolvesaproblembyusingthesolu)ontothesameproblemwithsimplerinputs.

•  Forarecursiontoterminate,theremustbespecialcasesforthesimplestvalues.

•  Designarecursivesolu)ontoaproblem.

11/18/16 Page 76

Page 43: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

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

Page 44: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Summary •  Reviewacomplexrecursionexamplethatcannotbesolvedwithasimpleloop.•  Thepermuta)onsofastringcanbeobtainedmorenaturallythroughrecursionthanwithaloop.

•  Usebacktrackingtosolveproblemsthatrequiretryingoutmul)plepaths.•  Backtrackingexaminespar)alsolu)ons,abandoningunsuitableonesandreturningtoconsiderothercandidates.

11/18/16 Page 78

Page 45: Professor Donald J. Patterson - Call Pattern of Recursive Fib() …djp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture... · 2016-11-18 · ch11.pptx Author: Donald Patterson

Summary •  Recognizethephenomenonofmutualrecursioninanexpressionevaluator.•  Inamutualrecursion,coopera)ngfunc)onsormethodscalleachotherrepeatedly.

11/18/16 Page 79