11/16/16 page 23 · 2016-11-16 · substring palindromes (1) • rather than tes%ng whether the...

Post on 13-Aug-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

11/16/16 Page 22

11/16/16 Page 23

11/16/16 Page 24

Recursive Helper functions •  Some%mesitiseasiertofindarecursivesolu%onifyoumakeaslightchangetotheoriginalproblem.

•  Considerthepalindrometestofprevioussec%on.

•  Itisabitinefficienttoconstructnewstringobjectsineverystep.

11/16/16 Page 25

Substring Palindromes (1) •  Ratherthantes%ngwhetherthesentenceisapalindrome,checkwhetherasubstringisapalindrome:

11/16/16 Page 26

##Recursivelytestswhetherasubstringis#apalindrome.#@paramtextastringthatisbeingchecked#@paramstarttheindexofthefirstcharacterofthesubstring#@paramendtheindexofthelastcharacterofthesubstring#@returnTrueifthesubstringisapalindrome#defsubstringIsPalindrome(text,start,end):

Substring Palindromes (2) •  Then,simplycallthehelperfunc%onwithposi%onsthattesttheen%restring:

11/16/16 Page 27

defisPalindrome(text):returnsubstringIsPalindrome(text,0,len(text)–1)

Recursive Helper function

11/16/16 Page 28

Continued

defsubstringIsPalindrome(text,start,end):#Separatecaseforsubstringsoflength0and1.ifstart>=end:returnTrueelse:#Getfirstandlastcharacters,convertedtolowercase.first=text[start].lower()last=text[end].lower()

Recursive Helper Function

11/16/16 Page 29

iffirst.isalpha()andlast.isalpha():iffirst==last:#Testsubstringthatdoesn’tcontainthematching#letters.returnsubstringIsPalindrome(text,start+1,end-1)else:returnFalseelifnotlast.isalpha():#Testsubstringthatdoesn’tcontainthelastcharacter.returnsubstringIsPalindrome(text,start,end-1)else:#Testsubstringthatdoesn’tcontainthefirst#character.returnsubstringIsPalindrome(text,start+1,end)

11.4 The Efficiency of Recursion •  Fibonaccisequence:Sequenceofnumbersdefinedby

f1 = 1 f2 = 1 fn = fn-1 + fn-2

•  Firsttenterms:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55

Page 30 11/16/16

Recursivefib.py

Page 31 11/16/16

Efficiency of Recursion •  Recursiveimplementa%onoffib()isstraighForward.

•  Watchtheoutputcloselyasyourunthetestprogram.

•  Firstfewcallstofib()arequitefast.

•  Forlargervalues,theprogrampausesanamazinglylong%mebetweenoutputs.

•  Tofindouttheproblem,let’sinserttracemessages.

11/16/16 Page 32

Recursivefibtracer.py: 1

Page 33 11/16/16

Recursivefibtracer.py: 2

Page 34 11/16/16

Call Pattern of Recursive Fib() Function

11/16/16 Page 35

Efficiency of Recursion •  Thefunc%ontakessolongbecauseitcomputesthesamevaluesover

andover.

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

•  Imitatethepencil-and-paperprocesstoavoidcompu%ngthevaluesmorethanonce.

11/16/16 Page 36

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

•  Inmostcases,therecursivesolu%onisonlyslightlyslower.

•  Theitera%veisPalindrome()performsonlyslightlybeLerthanrecursivesolu%on.

•  Eachrecursivefunc.oncalltakesacertainamountofprocessor.me

11/16/16 Page 37

Loopfib.py(1)

Page 38 11/16/16

Loopfib.py(2)

Page 39 11/16/16

Efficiency of Recursion •  Smartcompilerscanavoidrecursivefunc%oncallsiftheyfollowsimplepaLerns.

•  Mostcompilersdon’tdothat

•  Inmanycases,arecursivesolu%oniseasiertounderstandandimplementcorrectlythananitera%vesolu%on.

•  ‘Toiterateishuman,torecursedivine.’-L.PeterDeutsch

Page 40 11/16/16

Iterative IsPalindrome()Function

Page 41

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/16/16

11.5 Permutations •  Designaclassthatwilllistallpermuta%onsofstring,whereapermuta%onisarearrangementoftheleLers

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

11/16/16 Page 42

Generate All Permutations (1) •  Generateallpermuta%onsthatstartwith'e',then'a',then't'

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

11/16/16 Page 43

Generate All Permutations (2) •  Generateallpermuta%onsthatstartwith'e',then'a',then't'

•  Togeneratepermuta%onsstar%ngwith'e',weneedtofindallpermuta%onsof"at"

•  Thisisthesameproblemwithsimplerinputs

•  Userecursion

11/16/16 Page 44

Implementing Permutations() Function

•  Loopthroughallposi%onsinthewordtobepermuted

•  Foreachofthem,computetheshorterwordobtainedbyremovingtheithleLer:

11/16/16 Page 45

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

shorterPermutations=permutations(shorter)

•  Computethepermuta%onsoftheshorterword:

Implementing Permutations() Function •  AddtheremovedleLertothefrontofallpermuta%onsoftheshorterword:

11/16/16 Page 46

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

•  Specialcaseforthesimpleststring,theemptystring,whichhasasinglepermuta%on-itself

Permutations.py (1)

Page 47 11/16/16

Permutations.py (2)

Page 48 11/16/16

Backtracking •  Backtrackingexaminespar%alsolu%ons,abandoningunsuitableonesandreturningtoconsiderothercandidates

•  Canbeusedto•  solvecrosswordpuzzles

•  escapefrommazes

•  findsolu%onstosystemsthatareconstrainedbyrules

11/16/16 Page 49

Backtracking Characteristic Properties 1.  Aproceduretoexamineapar%alsolu%onanddeterminewhether

to:

I.  acceptitasanactualsolu%onor,

II.  abandonit(becauseiteitherviolatessomerulesorcanneverleadtoavalidsolu%on)

2.  Aproceduretoextendapar%alsolu%on,genera%ngoneormoresolu%onsthatcomeclosertothegoal

11/16/16 Page 50

Recursive Backtracking Algorithm Solve(partialSolution)

Examine(partialSolution).

Ifaccepted

AddpartialSolutiontothelistofsolutions.

Elseifnotabandoned

Foreachpinextend(partialSolution)

Solve(p)

11/16/16 Page 51

Eight Queens Problem •  Problem:posi%oneightqueensonachessboardsothatnoneofthemaLacksanotheraccordingtotherulesofchess

•  Asolu%on:

11/16/16 Page 52

top related