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

31
11/16/16 Page 22

Upload: others

Post on 13-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

11/16/16 Page 22

Page 2: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

11/16/16 Page 23

Page 3: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

11/16/16 Page 24

Page 4: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Recursive Helper functions •  Some%mesitiseasiertofindarecursivesolu%onifyoumakeaslightchangetotheoriginalproblem.

•  Considerthepalindrometestofprevioussec%on.

•  Itisabitinefficienttoconstructnewstringobjectsineverystep.

11/16/16 Page 25

Page 5: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

11/16/16 Page 26

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

Page 6: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

11/16/16 Page 27

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

Page 7: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

Page 8: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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)

Page 9: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

Page 10: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Recursivefib.py

Page 31 11/16/16

Page 11: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Efficiency of Recursion •  Recursiveimplementa%onoffib()isstraighForward.

•  Watchtheoutputcloselyasyourunthetestprogram.

•  Firstfewcallstofib()arequitefast.

•  Forlargervalues,theprogrampausesanamazinglylong%mebetweenoutputs.

•  Tofindouttheproblem,let’sinserttracemessages.

11/16/16 Page 32

Page 12: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Recursivefibtracer.py: 1

Page 33 11/16/16

Page 13: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Recursivefibtracer.py: 2

Page 34 11/16/16

Page 14: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Call Pattern of Recursive Fib() Function

11/16/16 Page 35

Page 15: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Efficiency of Recursion •  Thefunc%ontakessolongbecauseitcomputesthesamevaluesover

andover.

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

•  Imitatethepencil-and-paperprocesstoavoidcompu%ngthevaluesmorethanonce.

11/16/16 Page 36

Page 16: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

•  Inmostcases,therecursivesolu%onisonlyslightlyslower.

•  Theitera%veisPalindrome()performsonlyslightlybeLerthanrecursivesolu%on.

•  Eachrecursivefunc.oncalltakesacertainamountofprocessor.me

11/16/16 Page 37

Page 17: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Loopfib.py(1)

Page 38 11/16/16

Page 18: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Loopfib.py(2)

Page 39 11/16/16

Page 19: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Efficiency of Recursion •  Smartcompilerscanavoidrecursivefunc%oncallsiftheyfollowsimplepaLerns.

•  Mostcompilersdon’tdothat

•  Inmanycases,arecursivesolu%oniseasiertounderstandandimplementcorrectlythananitera%vesolu%on.

•  ‘Toiterateishuman,torecursedivine.’-L.PeterDeutsch

Page 40 11/16/16

Page 20: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

Page 21: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

11.5 Permutations •  Designaclassthatwilllistallpermuta%onsofstring,whereapermuta%onisarearrangementoftheleLers

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

11/16/16 Page 42

Page 22: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

Page 23: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

Page 24: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Implementing Permutations() Function

•  Loopthroughallposi%onsinthewordtobepermuted

•  Foreachofthem,computetheshorterwordobtainedbyremovingtheithleLer:

11/16/16 Page 45

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

shorterPermutations=permutations(shorter)

•  Computethepermuta%onsoftheshorterword:

Page 25: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Implementing Permutations() Function •  AddtheremovedleLertothefrontofallpermuta%onsoftheshorterword:

11/16/16 Page 46

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

•  Specialcaseforthesimpleststring,theemptystring,whichhasasinglepermuta%on-itself

Page 26: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Permutations.py (1)

Page 47 11/16/16

Page 27: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Permutations.py (2)

Page 48 11/16/16

Page 28: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Backtracking •  Backtrackingexaminespar%alsolu%ons,abandoningunsuitableonesandreturningtoconsiderothercandidates

•  Canbeusedto•  solvecrosswordpuzzles

•  escapefrommazes

•  findsolu%onstosystemsthatareconstrainedbyrules

11/16/16 Page 49

Page 29: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

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

Page 30: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Recursive Backtracking Algorithm Solve(partialSolution)

Examine(partialSolution).

Ifaccepted

AddpartialSolutiontothelistofsolutions.

Elseifnotabandoned

Foreachpinextend(partialSolution)

Solve(p)

11/16/16 Page 51

Page 31: 11/16/16 Page 23 · 2016-11-16 · Substring Palindromes (1) • Rather than tes%ng whether the sentence is a palindrome, check whether a substring is a palindrome: 11/16/16 Page

Eight Queens Problem •  Problem:posi%oneightqueensonachessboardsothatnoneofthemaLacksanotheraccordingtotherulesofchess

•  Asolu%on:

11/16/16 Page 52