CP164 Final: Types of Recursion

46 views2 pages
14 Jun 2018
School
Course
Professor
Types of Recursion
When considering how to write a recursive algorithm, it is useful to know some basic
different approaches to recursion.
Fruitful Recursion
Fruitful recursion simply uses a function that returns one or more values. This is nothing
new to us - we have written many functions that return something. In the context of
recursion, however, this means that the recursion relies on the fact that each call returns a
value that will be used in the recursion.
We will demonstrate this approach by reversing the contents of a list. This algorithm solves
the problem by starting at the ends of the list, swapping the values at the ends, then
working inwards with the next pair of values until the middle of the list is reached and
there are no values left to swap. As part of these examples we will use a swap function to
'swap' two elements of a list:
def swap(data, i, j):
temp = data[i]
data[i] = data[j]
data[j] = temp
return
In this example, we reverse the contents of a Python list by changing slices of the list:
def rev_list_f(data):
n = len(data)
if n > 1:
swap(data, 0, n-1)
data[1:n - 1] = rev_list_f(data[1:n - 1])
return data
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

Document Summary

When considering how to write a recursive algorithm, it is useful to know some basic different approaches to recursion. Fruitful recursion simply uses a function that returns one or more values. This is nothing new to us - we have written many functions that return something. In the context of recursion, however, this means that the recursion relies on the fact that each call returns a value that will be used in the recursion. We will demonstrate this approach by reversing the contents of a list. As part of these examples we will use a swap function to. "swap" two elements of a list: def swap(data, i, j): temp = data[i] data[i] = data[j] data[j] = temp return. In this example, we reverse the contents of a python list by changing slices of the list: def rev_list_f(data): n = len(data) if n > 1: swap(data, 0, n-1) data[1:n - 1] = rev_list_f(data[1:n - 1]) return data.

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