Lilian Blot Recursion Autumn 2012 TPOP 1. Lilian Blot Recursion Autumn 2012 TPOP 2.

Slides:



Advertisements
Similar presentations
Mathematical Preliminaries
Advertisements

2. Getting Started Heejin Park College of Information and Communications Hanyang University.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
Chapter 1 The Study of Body Function Image PowerPoint
1 Copyright © 2013 Elsevier Inc. All rights reserved. Appendix 01.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
Chapter 7. Binary Search Trees
Lecture 15 Linked Lists part 2
CS16: Introduction to Data Structures & Algorithms
Lilian Blot Announcements Teaching Evaluation Form week 9 practical session Formative Assessment week 10 during usual practical sessions group 1 Friday.
Computer Science Recursion Yuting Zhang Allegheny College, 04/24/06.
Lilian Blot 11 Spring 2014 TPOP 1. Lilian Blot 22 Spring 2014 TPOP 2.
Randomized Algorithms Randomized Algorithms CS648 1.
Chapter 17 Linked Lists.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Singly Linked Lists What is a singly-linked list? Why linked lists?
Linked Lists Chapter 4.
Data Structures: A Pseudocode Approach with C
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
ITEC200 Week04 Lists and the Collection Interface.
Data Structures Using C++
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 Linked Lists A linked list is a sequence in which there is a defined order as with any sequence but unlike array and Vector there is no property of.
Hash Tables.
Lilian Blot CORE ELEMENTS PART I Python Language Autumn 2013 TPOP 1.
VOORBLAD.
Review Pseudo Code Basic elements of Pseudo code
BIOLOGY AUGUST 2013 OPENING ASSIGNMENTS. AUGUST 7, 2013  Question goes here!
Factor P 16 8(8-5ab) 4(d² + 4) 3rs(2r – s) 15cd(1 + 2cd) 8(4a² + 3b²)
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
© 2012 National Heart Foundation of Australia. Slide 2.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
Understanding Generalist Practice, 5e, Kirst-Ashman/Hull
25 seconds left…...
Binary Search Trees Ravi Chugh March 28, Review: Linked Lists Goal: Program that keeps track of friends Problem: Arrays have fixed length Solution:
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
CSE Lecture 17 – Balanced trees
Starting Out with Java: From Control Structures through Objects
PSSA Preparation.
Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
Foundations of Data Structures Practical Session #7 AVL Trees 2.
§2 Binary Trees Note: In a tree, the order of children does not matter. But in a binary tree, left child and right child are different. A B A B andare.
Introduction to Recursion and Recursive Algorithms
CPSC 322, Lecture 5Slide 1 Uninformed Search Computer Science cpsc322, Lecture 5 (Textbook Chpt 3.5) Sept, 14, 2012.
Lecture Objectives  Learn how to think recursively  Trace a recursive method  Prove a recursive method is correct  Write recursive algorithms and methods.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Binary Search Tree Smt Genap
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
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.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Binary Search Tree (BST)
Presentation transcript:

Lilian Blot Recursion Autumn 2012 TPOP 1

Lilian Blot Recursion Autumn 2012 TPOP 2

Lilian Blot Overview What is recursion? Recursive versus Iterative Optimisation… tail recursion elimination Autumn 2012 TPOP 3

Lilian Blot Definition From Wikipedia: In mathematical logic and computer science, recursive definition (or inductive definition) is used to define an object in terms of itself. (Aczel 1978:740ff). Autumn 2012 TPOP 4

Lilian Blot Definition In mathematics and computer science, a class of objects or methods exhibit recursive behaviour when they can be defined by two properties: 1. A simple base case (or cases), and 2. A set of rules which reduce all other cases toward the base case. Autumn 2012 TPOP 5

Lilian Blot Factorial: n! the factorial function n! is defined by the rules 1. 0! = 1 2. (n+1)! = (n+1)·n! Recursive approaches rely on the fact that it is usually simpler to solve a smaller problem than a larger one. The recursive case usually contains a call to the very function being executed. This call is known as a recursive call. Autumn 2012 TPOP 6

Lilian Blot def factorial_rec(n): return n * factorial_rec(n - 1) Code Recursive Code WRONG Autumn 2012 TPOP 7 def factorial_rec(n): if (n == 0): ## Base case return 1 else: return n * factorial_rec(n - 1) ## Recursive call Code Recursive def factorial_iter(n): total = 1 for i in range(1,n+1): total = total * i return total Code Iterative

Lilian Blot Recursion vs Iteration All recursion can be written in an iterative form Autumn 2012 TPOP 8

Lilian Blot Recursion vs Iteration Question: Does using recursion usually make your code faster? Answer: No. Autumn 2012 TPOP 9

Lilian Blot Recursion vs Iteration Question: Does using recursion usually use less memory? Answer: No. Autumn 2012 TPOP 10

Lilian Blot Recursion vs Iteration Question: Then why use recursion? Answer: It sometimes makes your code much simpler! Autumn 2012 TPOP 11

Lilian Blot How does it work? When a recursive call is made, the method clones itself, making new copies of: the code the local variables (with their initial values), the parameters Each copy of the code includes a marker indicating the current position. When a recursive call is made, the marker in the old copy of the code is just after the call; the marker in the "cloned" copy is at the beginning of the method. When the method returns, that clone goes away but the previous ones are still there, and know what to execute next because their current position in the code was saved (indicated by the marker). See Wills lecture 13 for another description Autumn 2012 TPOP 12

Lilian Blot Example: factorial_rec(2) Autumn 2012 TPOP 13 factorial_rec(2): if (2 == 0): ## Base case return 1 else: return 2 * factorial_rec(2 – 1) Code Recursive factorial_rec(1): if (1 == 0): ## Base case return 1 else: return 1 * factorial_rec(1 - 1) factorial_rec(0): if (0 == 0): ## Base case return 1 else: return 1 * factorial_rec(0 - 1)

Lilian Blot Example: factorial_rec(2) Autumn 2012 TPOP 14 factorial_rec(2): if (2 == 0): ## Base case return 1 else: return 2 * factorial_rec(2 – 1) Code Recursive factorial_rec(1): if (1 == 0): ## Base case return 1 else: return 1 * factorial_rec(1 - 1) factorial_rec(0): if (0 == 0): ## Base case return 1 else: return 1 * factorial_rec(0 - 1) 1 1 2

Lilian Blot Tail recursion a tail call is a subroutine call that happens inside another function as its final action Tail-call optimization is where you are able to avoid allocating a new stack frame for a function the calling function will simply return the value that it gets from the called function. Traditionally, tail call elimination is optional in functional programming languages, tail call elimination is often guaranteed by the language standard Python does not implement tail call elimination Autumn 2012 TPOP 15

Lilian Blot Summary Use recursion for clarity, and (sometimes) for a reduction in the time needed to write and debug code, not for space savings or speed of execution. Remember that every recursive method must have a base case (rule #1). Also remember that every recursive method must make progress towards its base case (rule #2). Autumn 2012 TPOP 16

Lilian Blot Summary Every recursive function can be written as an iterative function Recursion is often simple and elegant, can be efficient, and tends to be underutilized. Consider using recursion when solving a problem! Autumn 2012 TPOP 17

Lilian Blot AN IMPLEMENTATION USING OBJECT ORIENTED PROGRAMMING (OOP) Binary Search Tree TPOP 18 Spring 2013

Lilian Blot Review BST A binary tree is a special case of a tree in which nodes have a degree of at most 2 The two children of a node are called the left and right child Binary search trees are a type of binary tree which are extremely useful for storing and retrieving ordered data: Each node is labelled with a key Nodes in the left subtree have keys smaller than that of the root Nodes in the right subtree have keys greater than that of the root TPOP 19 Spring 2013

Lilian Blot Review BST TPOP 20 Spring 2013

Lilian Blot Review BST TPOP 21 _Node Spring 2013

Lilian Blot OOP Implementation Encapsulation as Information hiding Data belonging to one object is hidden from other objects. Know what an object can do, not how it does it. NOT allowed to change key value allowed to change datum/data, and left/right children TPOP 22 class _Node: def __init__(self, key, data): assert key is not None, 'BST_Node constructor: Illegal Argument ' self._key = key self._data = data self._left = None self._right = None Code OOP Spring 2013

Lilian Blot OOP Implementation What _Node can do: (see binary_search_tree.py) TPOP 23 class _Node: def __init__(self, key, data): # the constructor def key(self): # returns the key def getData(self): # returns the data def getLeft(self): # return the left child def getRight(self): #return the right child def setData(self, data): # change the data def setLeft(self, bstNode): # change the left child def setRight(self, bstNode): # change the right child def isleaf(self): # returns True if the node is a leaf Code OOP Spring 2013

Lilian Blot OOP Implementation What BSTree can do: (see binary_search_tree.py) TPOP 24 class BSTree: def __init__(self, bst_node): # the constructor def isempty(self): def getLeftTree (self): # returns the left child as a BSTree Object def setLeftBranch(self, bst): def hasLeftBranch (self): # returns True if left branch not empty def insert(self, key, data): # insert a new node def printInOrder(self): # returns a string representing the BST # using In-Order-Traversal algorithm Code OOP Spring 2013

Lilian Blot Insertion See Code binary_search_tree.py TPOP to insert Spring 2013

Lilian Blot Insertion See Code binary_search_tree.py TPOP to insert Spring 2013

Lilian Blot Insertion See Code binary_search_tree.py TPOP to insert match Spring 2013

Lilian Blot Insertion See Code binary_search_tree.py TPOP Spring 2013

Lilian Blot Summary You should be familiar with Encapsulation and information hiding Implementing classes in OOP Recursive algorithm Binary Search tree implementation TPOP 29 Spring 2013

Lilian Blot Exercises implement a search/retrieve method in the BSTree class. The method should return None if no element with the given key exists, a tuple (key,data) otherwise. implement a remove method in the BSTree class to remove the element with the given key from the BST. see Wills Lecture slides (week 10 Autumn term) Spring 2013 TPOP 30

Lilian Blot Exercise: the greatest common divisor Consider finding the greatest common divisor, the gcd, of two numbers. For example, the gcd of 30 and 70 is 10, since 10 is the largest number that divides both 30 and 70 evenly. Euclid Algorithm: 1. gcd(a,b) is b if a divided by b has a remainder of zero 2. gcd(a,b) is gcd(b, a % b)otherwise Autumn 2012 TPOP 31

Lilian Blot Exercises: sumItems(linkedList) ## linked list of int Autumn 2012 TPOP 32