Docsity

7. Recursion - Recursive Functions.pptx, Summaries of Computer science

Partial preview of the text

Download 7. Recursion - Recursive Functions.pptx and more Summaries Computer science in PDF only on Docsity!

Paper 1

Recursion / Recursive

Functions

Objectives

  • (^) Understand the term recursion and why it’s used in

programming

Be able to solve simple problems using recursion

  • (^) Construct programs that use recursion

Python Recursion

In Python, a function is recursive if it calls itself and

has a termination condition.

Why a termination condition? To stop the function from

calling itself ad infinity.

Python Sum of List (Iterative)

def sumOfList(mylist): sumof = 0 # Add every number in the list. for i in range(mylist)): sumof = sumof + list[i] # Return the sum. return sumof print (sumOfList([ 5 , 7 , 3 , 8 , 10 ]))

Copy the following code into Python IDLE and run the code, what's the output?

So, which method is best? Well, obviously it depends on what you're trying to do - not all processes will provide an obvious recursive solution. Where they exist, recursive solutions tend to be more elegant, but can potentially be more difficult to understand (an important point to bear in mind if other people are going to be maintaining your code).

Iterative vs. Recursion

def sumOfList(mylist): if len(mylist) == 1 : return mylist[ 0 ] else : return mylist[ 0 ] + sumOfList(mylist[ 1 :]) print (sumOfList([ 5 , 7 , 3 , 8 , 10 ])) def sumOfList(mylist): sumof = 0 for i in range(mylist): sumof = sumof + list[i] return sumof print (sumOfList([ 5 , 7 , 3 , 8 , 10 ]))

Recursion / Recursive Programs

Limitations of Recursion

Every time a function calls itself it stores some data in

memory. So, a recursive function could hold much more memory than a traditional function. Python stops the function calls after a depth of 1000 calls. You can change this with:

import sys

sys.setrecursionlimit( 5000 )

)

Challenge 2 – Fibonacci Sequence

Anyone remember/know what Fibonacci sequence is?

In mathematics, the Fibonacci numbers are the numbers

in the following integer sequence, called the Fibonacci

sequence, and characterized by the fact that every

number after the first two is the sum of the two preceding

ones:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

Challenge 3 – Python Turtle Recursion

Using your knowledge of recursion can you create

patterns with Python Turtle using it.