recursion, search

54
Recursion, Search

Upload: karena

Post on 22-Mar-2016

61 views

Category:

Documents


0 download

DESCRIPTION

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

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.

Spot checkWrite the program in python to implement the solution described hereIf 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 peg

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 = 1 else: for i in range(1,n): fact = fact * i return fact

number=int(raw_input("Enter a positive integer: "))result = factorial(number)\print '%d! is %d %(number,result)=======Enter a positive integer: 55! is 24Spot checkTrace this code. def convertBinary(n): if (n