Lecture12-Recursion-3pp

# n1 n 1 2 3 n 1 recursion selfreference n n n

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1); Now evaluates to 4 * 6 20 Factorial  ­ Non ­recursive version • We can solve this problem using itera5on as well… # factorial function using iteration instead of recursion def factorial(an_int): product_so_far = 1 for index in range(an_int,0,-1): product_so_far = index*product_so_far return product_so_far • For some problems, loops are be`er. For others, recursion. Some5mes both work easily. 21 7 13 ­11 ­04 Recursive Func,ons  ­ Sum of the ﬁrst N numbers Example 1 + 2 + 3 . . . N ­1 + N ∑1 ∑2 ∑3 ∑N-1 recursion = selfreference ∑N ∑N = N + ∑N-1 ∑N-1 = N - 1 + ∑N-2 ∑N-2 = N - 2 + ∑N-3 ... ∑3 = 3 + ∑2 ∑2 = 2 + ∑1 ∑1 = 1 22 Recursion is a form of repe,,on 1 + 2 + 3 . . . N ­1 + N ∑1 ∑2 ∑3 ∑N-1 ∑N ∑N = N + ∑N-1 ∑N-1 = N - 1 + ∑N-2 ∑N-2 = N - 2 + ∑N-3 ... ∑3 = 3 + ∑2 ∑2 = 2 + ∑1 ∑1 = 1 23 When does the recursion stop? • Just like with loops, we need a way to stop   While loop: stop when the Bool...
View Full Document

## This document was uploaded on 03/02/2014.

Ask a homework question - tutors are online