CP164 Final: Recursion

35 views2 pages
14 Jun 2018
School
Course
Professor
Recursion
In-Place Recursion
In-place recursion uses functions that generally do not return values, rather they manipulate the
contents of the data structures they use in-place. In this example we want to reverse the contents
of a Python list by swapping elements of the list in-place. In order to do this the function requires
information about the elements to swap - this requires an auxiliary function with two additional
parameters:
def rev_list_ip(data):
rev_list_ip_aux(data, 0, len(data) - 1)
return
def rev_list_ip_aux(data, m, n):
if n > m:
swap(data, m, n)
rev_list_ip_aux(data, m + 1, n - 1)
return
Sample call:
>>> x = [1, 2, 3, 4, 5]
>>> rev_list_ip(x)
>>> print x
[5, 4, 3, 2, 1]
rev_list_ip passes the indices of the first and last elements in the data list to its auxiliary
function and lets the auxiliary function do the rest of the work.
The auxiliary function first determines whether or not it has already swapped all of the elements
in the list. Note that determining the length of the list in this case is not useful because the entire
list is used in each call to the function. The base case thus relies on the relative values of m and n.
It then swaps two elements of the list as determined by the values of m and n. The recursive call
passes a reference to the list and brings m and n closer together. The function does not return a
value (and is therefore not fruitful).
The following diagram shows how the in-place recursion is handled:
In-Place Recursion
Tree Recursion
Tree Recursion is defined as recursion in which there are possibly multiple recursive calls within
a function, thus forming a 'tree' of recursive calls. The classic Fibonacci recursive function is an
example of tree recursion:
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers

Related Documents

Related Questions