Recursion UW CSE 160 Winter 2016

Slides:



Advertisements
Similar presentations
CS 206 Introduction to Computer Science II 02 / 27 / 2009 Instructor: Michael Eckmann.
Advertisements

Recursion Michael Ernst UW CSE 140 To seal: moisten flap, fold over, and seal.
Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
Recursion Michael Ernst CSE 190p University of Washington To seal: moisten flap, fold over, and seal.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Algorithms. Problems, Algorithms, Programs Problem - a well defined task. –Sort a list of numbers. –Find a particular item in a list. –Find a winning.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Section Section Summary Recursive Algorithms Proving Recursive Algorithms Correct Recursion and Iteration (not yet included in overheads) Merge.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Algorithms Friday 7th Week. Algorithms What is an Algorithm? –A series of precise steps, known to stop eventually, to solve a problem –NOT necessarily.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
© by Kenneth H. Rosen, Discrete Mathematics & its Applications, Sixth Edition, Mc Graw-Hill, 2007 Chapter 4 (Part 3): Mathematical Reasoning, Induction.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
More on Efficiency Issues. Greatest Common Divisor given two numbers n and m find their greatest common divisor possible approach –find the common primes.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recitation 8 Programming for Engineers in Python.
Quicksort This is probably the most popular sorting algorithm. It was invented by the English Scientist C.A.R. Hoare It is popular because it works well.
Recursion COMP x1 Sedgewick Chapter 5. Recursive Functions problems can sometimes be expressed in terms of a simpler instance of the same problem.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS212: Data Structures and Algorithms
Recursive Algorithms Section 5.4.
Chapter 19: Recursion.
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Chapter 4 (Part 3): Mathematical Reasoning, Induction & Recursion
CSC 222: Object-Oriented Programming
RECURSION.
Decrease-and-Conquer Approach
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion CSE 2320 – Algorithms and Data Structures
Teach A level Computing: Algorithms and Data Structures
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Searching CSCE 121 J. Michael Moore.
Applied Algorithms (Lecture 17) Recursion Fall-23
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion UW CSE 160 Winter 2017
Recursion Spring 2015 UW CSE 160
Recursion UW CSE 160 Spring 2018
Programming application CC213
CS201: Data Structures and Discrete Mathematics I
Recursion Winter 2014 UW CSE 140
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Mathematical Background 2
Recursion Taken from notes by Dr. Neil Moore
Java Programming: Chapter 9: Recursion Second Edition
CS 1114: Sorting and selection (part two)
Recursion.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Recursion Review Spring 2019 CS 1110
Recursion Examples.
Lecture 6 - Recursion.
Presentation transcript:

Recursion UW CSE 160 Winter 2016 To seal: moisten flap, fold over, and seal UW CSE 160 Winter 2016

Three recursive algorithms Sorting GCD (greatest common divisor) Exponentiation Used in cryptography, which protects information and communication

Sorting a list Python’s sorted function returns a sorted version of a list. sorted([3, 1, 4, 1, 5, 9])  [1, 1, 3, 4, 5, 9] How could you implement sorted? Idea (“quicksort”, invented in 1960): Choose an arbitrary element (the “pivot”) Collect the smaller items and put them on its left Collect the larger items and put them on its right Sir Anthony Hoare

First version of quicksort (broken) def quicksort(thelist): """Return a sorted version of thelist.""" pivot = thelist[0] smaller = [elt for elt in thelist if elt < pivot] larger = [elt for elt in thelist if elt > pivot] return smaller + [pivot] + larger print quicksort([3, 1, 4, 1, 5, 9])  [1, 1, 3, 4, 5, 9] There are three problems with this definition Write a test case for each problem Problems: The “smaller” and “larger” lists elements aren’t themselves sorted Fails if the input list is empty Duplicate elements equal to the pivot are lost

Problems with first version of quicksort The “smaller” and “larger” lists aren’t sorted Fails if the input list is empty Duplicate elements equal to the pivot are lost

Final version of quicksort def quicksort(thelist): """Return a sorted version of thelist.""" if len(thelist) < 2: return thelist pivot = thelist[0] smaller = [elt for elt in thelist if elt < pivot] pivots = [elt for elt in thelist if elt == pivot] larger = [elt for elt in thelist if elt > pivot] return quicksort(smaller) + pivots + quicksort(larger)

General form of a recursive algorithm Determine whether the problem is small or large If the problem is small: (“base case”) Solve the whole thing If the problem is large: (“recursive case”) Divide the problem, creating one or more smaller problems Ask someone else to solve the smaller problems Recursive call to do most of the work (Maybe) Do a small amount of postprocessing on the result(s) of the recursive call(s)

Recursion design philosophy Recursion expresses the essence of divide and conquer Solve a smaller subproblem(s), then Use the answer(s) to solve the original problem Passing the buck: I am willing to do a small amount of work, as long as I can offload most of the work to someone else. Wishful thinking: If someone else solves most of the problem, then I will do the rest.

Decomposition for recursion List algorithms: Base case: short (or empty) list Recursive case: process all but the first element of the list, or The smaller subproblem is only a tiny bit smaller The postprocessing combines the first element of the list with the recursive result half of the list Often recursively process both halves The postprocessing combines the two recursive results Numeric algorithms: Base case: small number (often 1 or 0) Recursive case: process a smaller value 1 less than the original value half of the original value … File system: Base case: single file Recursive case: process a subdirectory Geographical algorithms: Base case: small area Recursive case: smaller part of a map (or other spatial representation)

Recursion: base and inductive cases A recursive algorithm always has: a base case (no recursive call) an inductive or recursive case (has a recursive call) solves a smaller problem What happens if you leave out the base case? What happens if you leave out the inductive case?

Factorial def fact(num): """ Assumes num is an int > 0, return n!""" if num == 1: return num else: return num * fact(num - 1) print fact(3) print fact(1) print fact(2)

Sum List def sum_list(lst): """Returns sum of numbers in list. Returns zero for an empty list.""" if len(lst) == 0: return 0 else: return lst[0] + sum_list(lst[1:]) sum_list([1, 3, 6])

Fibonacci def fib(n): """Returns the nth Fibonacci number.""" if n == 0 or n == 1: return 1 else: return fib(n - 1) + fib(n - 2) print fib(6)

GCD (greatest common divisor) gcd(a, b) = largest integer that divides both a and b gcd(4, 8) = 4 gcd(15, 25) = 5 gcd(16, 35) = 1 How can we compute GCD?

Euclid’s method for computing GCD (circa 300 BC, still commonly used!) a if b = 0 gcd(a, b) = gcd(b, a) if a < b gcd(a-b, b) otherwise

Python code for Euclid’s algorithm def gcd(a, b): """Return the greatest common divisor of a and b.""" if b == 0: return a elif a < b: return gcd(b, a) else: return gcd(a - b, b)

Exponentiation Goal: Perform exponentiation, using only addition, subtraction, multiplication, and division. (Example: 34) def exp(base, exponent): """Return baseexponent. Exponent is a non-negative integer.""" if exponent == 0: return 1 else: return base * exp(base, exponent - 1) Example: exp(3, 4) 3 * exp(3, 3) 3 * (3 * exp(3, 2)) 3 * (3 * (3 * exp(3, 1))) 3 * (3 * (3 * (3 * exp(3, 0)))) 3 * (3 * (3 * (3 * 1)))

Faster exponentiation Suppose the exponent is even. Then, baseexponent = (base*base)exponent/2 Examples: 34 = 92 92 = 811 512 = 256 256 = 6253 New implementation: def exp(base, exponent): """Return baseexponent. Exponent is a non-negative integer.""" if exponent == 0: return 1 elif exponent % 2 == 0: return exp(base * base, exponent / 2) else: return base * exp(base, exponent - 1)

Comparing the two algorithms Original algorithm: 12 multiplications Fast algorithm: 5 multiplications exp(5, 12) 5 * exp(5, 11) 5 * 5 * exp(5, 10) 5 * 5 * 5 * exp(5, 9) … 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * exp(5, 0) 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 1 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 25 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 125 244140625 exp(5, 12) (5 * 5)6 exp(25, 6) (25 * 25)3 exp(625, 3) 625 * exp(625, 2) (625 * 625)1 625 * exp(390625, 1) 625 * 390625 * exp(390625, 0) 625 * 390625 * 1 625 * 390625 244140625 600 digits = 2000 bits Raise a number with 600 digits to a power. Speed matters: In cryptography, exponentiation is done with 600-digit numbers.

Recursion vs. iteration Any recursive algorithm can be re-implemented as a loop instead This is an “iterative” expression of the algorithm Any loop can be implemented as recursion instead Sometimes recursion is clearer and simpler Mostly for data structures with a recursive structure Sometimes iteration is clearer and simpler