Top Banner
Recursion, Search
53

Recursion, Search

Feb 24, 2016

Download

Documents

Selah

Recursion, Search. Recursion – the Easy Solution. Recursion is a technique for reducing a complex problem to repeated solution of easy problems. The book has some examples. I will do some different ones. Recursion and Induction. - PowerPoint PPT Presentation
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

Slide 1

Recursion, SearchRecursion the Easy SolutionRecursion is a technique for reducing a complex problem to repeated solution of easy problems.The book has some examples. I will do some different ones.Recursion and InductionInduction is a form of proof that relates a simple base case and an iterative process that proceeds from that base case. Recursion and induction are closely related ideas. Both are important tools for turning something apparently hard into something simple that gets repeated.Towers of HanoiMy favorite example of recursion.Puzzle invented by the French mathematician Edouard Lucas in 1883Given three pegs, one with a set of disks(8 in the original puzzle) of graduated sizes, move all the disks to a different pegnever put a larger disk on top of a smaller disk.See http://www.mazeworks.com/hanoi/ or http://www.mathsisfun.com/games/towerofhanoi.htmlSolve the puzzle with three disks, then with four disks.How would you describe the algorithm for solving this puzzle?Consider this solutionIf the pegs are numbered 1, 2, 3 and you want to move the n disks from peg 1 to peg 3 (destination peg), using peg 2 as an extra peg:If n = 1, move it to the destination pegOtherwiseMove the top n-1 disks to the extra pegMove the bottom disk to the destination pegMove the n-1 disks from the extra peg to the destination pegBe careful about the naming. Sometimes the extra peg is the destination at a step.Try this for n = 3, n = 4.

A really bad exampleFactorial (it is in the chapter, sadly)Recursion involves overhead. Dont force it on problems better solved other ways.Factorial is inherently iterative:n! = n*n-1*n-2*n-3..*1def factorial(n): fact = 1 if n == 0: fact = n else: for i in range(1,n): fact = fact * i return fact

result = factorial(5)print result

=======24Spot checkTrace this code. def convertBinary(n): if (n