Lecture Notes: Recurrence Relations and Algorithms
Verified
Added on Β 2023/01/13
|20
|6833
|97
AI Summary
This lecture notes covers topics such as recursive algorithms, Towers of Hanoi, and recurrence relations. It explains the concept of solving problems using recursion and provides an example of Towers of Hanoi problem. It also discusses the use of recurrence relations in generating sequences.
Contribute Materials
Your contribution can guide someoneβs learning journey. Share your
documents today.
Lecture Notes Computational Problem Solving Week 7: Recurrence Relations and Algorithms Contents Recursive Algorithms ............................................................................................................................................. 1 Towers of Hanoi .................................................................................................................................................... 1 Recurrence Relations ............................................................................................................................................ 5 Second Order Linear Homogeneous Recurrence Relations .................................................................................. 8 Application: Fibonacci and Lucas Recurrence Relations ....................................................................................... 9 Extension Topic: General Homogeneous Recurrence Relations ......................................................................... 11 Extension Topic: Non-homogeneous Recurrence Relations ........................................................................... 12 Recursion in Python ............................................................................................................................................ 13 Recursive Algorithms Recursive algorithms are those that call themselves. For example, to find the factorial of an integer is: 5! = 5 Γ 4 Γ 3 Γ 2 Γ 1 And more generally as: π! = π Γ(π β1)Γ(π β2)Γ β¦ Γ 3 Γ 2 Γ 1 As(π β1)! =(π β1)Γ(π β2)Γ β¦ Γ 3 Γ 2 Γ 1we can rewrite the above as: π! = π Γ(π β1)! Where1! = 1as a base condition. As we can see recursive algorithms have similar ideas to what we used to prove statements by mathematical induction. Towers of Hanoi This involves n discs of various sizes on three posts
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
The disc starts on one of the posts with the largest disc on the bottom of the stack, with the smaller discs resting on top of a larger disc, so ordered with respect to size. The exercise is to move all the discs to another post, with the largest on the bottom and the smallest on top without a larger disc resting on a small disc. The question is: what is the minimum number of moves needed? Understanding the Problem: Objective: Place the pile of discs on a different peg Constraints: - no disc can sit on a smaller disc - only top disc may be moved - you can only move one disc at a time We are being asked to work out the minimum number of moves to move the discs from one peg to another. We could build a model of the problem (as it was originally in Vietnam). Or we can use diagrams to help us model the moves. We cannot really restate the problem. The unknown is the minimum number of moves as well as the number of discs. Also, we are not sure how we can make those moves to obtain the minimal number of moves. We have not made any assumptions apart from the constraints of the problem and that there are a fixed number of pegs which is 3 (i.e. we are not generalising the number of pegs). Devising a Plan We havenβt solved this problem before. However, we have looked at noughts and crosses. In that problem we broke it down by seeing what happens if we add an extra column or row. We can do a similar approach here too. We can look at the number of moves for 1 disc, 2 discs, etc to see if we can build up a pattern. We can then look to see how we make those moves for 2 discs, 3 discs to see what happens if we add a disc to the source peg. We already said in part (1) that we can use diagrams to help us. We havenβt left anything out from the problem statement. To move three discs, we may find via trial and error:
Following a similar strategy, we may find the number of ways to move the discs when we have 2, 3, 4, etc discs. Number of discsNumber of movesbreakdown 111 231 + 1 + 1 373 + 1 + 3 4157 + 1 + 7 53115 + 1 + 15 Generalising this, we may find the number of moves is: (number of moves forπ β1discs) + 1 + (number of moves forπ β1discs) Alternatively, we may note that the number of moves is one less than a power of 2. Therefore, the number of moves is2πβ1. Hence givenπdiscs on a peg it will take2πβ1moves (minimum) to move the discs from one peg to another peg given the constraints. But, how do we make those moves? This is where the first strategy proves helpful. To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with lesser amount of discs, say β 1 or 2. We mark three towers with name,source,destinationandaux(only to help moving the discs). If we have only one disc, then it can easily be moved from source to destination peg. If we have 2 discs β β’First, we move the smaller (top) disc to aux peg. β’Then, we move the larger (bottom) disc to destination peg. β’And finally, we move the smaller disc from aux to destination peg. If we then say that the larger (bottom) disc is the rest of the discs and using the relationship between the number of moves: number of moves forπ β1discs) + 1 + (number of moves forπ β1discs), we can form a generalised strategy.
Approach: β’Recursively Move N-1 disc from source to Auxiliary peg. β’Move the last disc from source to destination. β’Recursively Move N-1 disc from Auxiliary to destination peg The steps to follow are: Step 1β Move n-1 discs fromsourcetoaux Step 2β Move nthdisc fromsourcetodest Step 3β Move n-1 discs fromauxtodest From which we can produce pseudo-code to solve the Towers of Hanoi problem. START Procedure Hanoi(disc, source, dest, aux) IF disc == 1, THEN move disc from source to dest ELSE Hanoi(disc - 1, source, aux, dest) // Step 1 move disc from source to dest // Step 2 Hanoi(disc - 1, aux, dest, source) // Step 3 END IF END Procedure STOP Which, in Python, is: defTowerOfHanoi(n , source, destination, auxiliary): ifn==1: print ("Move disc 1 from source",source,"to destination",destination) return TowerOfHanoi(n-1, source, auxiliary, destination) print("Move disc",n,"from source",source,"to destination",destination) TowerOfHanoi(n-1, auxiliary, destination, source) # test code n=4 TowerOfHanoi(n,'A','B','C') # A, C, B are the name of rods To test this, we may look at the solutions or prove it via induction. For the Tower of Hanoi, we have the number of moves,ππisππ= 2πβ1forπdiscs, this is ourπ(π).
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Base case,π(1):π1= 21β1 = 2 β 1 = 1. We know it takes one move to move one disc, soπ(1)is true. We assume thatπ(π): ππ= 2πβ1is true. Now, forπ(π+ 1): ππ+1= 2π+1β1 ππ+1=(ππ’πππππππππ£ππ ππππ’πππππ‘ππππ£πππππ ππ πππ‘βππππ‘π‘πππππ π) + (1πππ£ππ‘ππππ£ππ‘βππππ ππππ π) + (ππ’πππππππππ£ππ ππππ’πππππ‘ππππ£ππ‘βπππππ ππ πππππππ‘ππ‘βππππ πππ = ππ+ 1 + ππ= 2ππ+ 1 = 2(2πβ1)+ 1 = 2 Γ 2πβ2 + 1 = 21Γ 2πβ1 = 2π+1β1 Henceπ(π+ 1)is true provided thatπ(π)is true. Therefore, by mathematical induction, the number of moves for the Tower of Hanoi isππ= 2πβ1 We therefore have the number of moves is2πβ1. We note that: π1= 1 π2= 3 = 2 Γ 1 + 1 = 2π1+ 1 π3= 7 = 2 Γ 3 + 1 = 2π2+ 1 π4= 15 = 2 Γ 7 + 1 = 2π3+ 1 By looking at the pattern, we have ππ= 2ππβ1+ 1,π1= 1 As our recursive formula. Assessing the result: Our solutions meets the requirements, we have found the minimal number of moves and how to make those moves using recursion. We can then test the algorithm on 2 discs and 3 discs, etc and we get the correct number of moves as well as the method to achieve those moves. We could possibly make some aspects easier; however, the most simple solution in this case is the recursive approach Describing what we have learnt: We learnt that we can use recursion to help solve problems and strengthen the idea of breaking a problem up to look at simpler cases before generalising. This problem was difficult in that the approach used is different to the noughts and crosses problem due to the increased complexity of the solution and the exponential nature of number of moves rather than the quadratic nature. Documenting the solution: Reread our solution, is there anything that should be rewritten? Not in this case, we cannot see anything that is difficult to understand Recurrence Relations We have already met recurrence relations, although not formally defined what they are. Consider the following instructions for generating a sequence: 1.Start with 5
2.Given any term, add 3 to get the next term If we list the terms of this sequence, we obtain 5,8,11,14,17,β¦ The first term is 5 because of instruction 1. The second term is 8 because instruction 2 says to add 3 to 5 to get the next term, 8 The third term is 11 because instruction 2 says to add 3 to 8 to get the next term, 11, etc Instructions 1 and 2 do not give an explicit formula for the nth term of the sequence in the sense of providing a formula that we can plug n into to obtain the value of the nth term, but by computing term by term we can eventually compute any term of the sequence. If we denote the sequence asπ1, π2,β¦, we may rephrase instruction 1 as π1= 5 And instruction 2 as: ππ= ππβ1+ 3,π β₯ 2 π1= 5 ππ= ππβ1+ 3,π β₯ 2 If we takeπ= 2, we obtainπ2= π1+ 3 = 5 + 3 = 8 If we takeπ= 3, we obtainπ3= π2+ 3 = 8 + 3 = 11 We can then compute any term in the sequence just as we did with instructions 1 and 2. The instructions above are equivalent to this. This equation is an example of a recurrence relation. A recurrence relation defines a sequence by giving the nth value in terms of its previous values. In order for a recurrence relation to define a sequence, a start up value (or initial conditions) must be given. Consider the following instructions for generating a sequence: 1.Start with 5 2.Given any term, add 3 to get the next term The following forms the function recursively (on the left) and iteratively (on the right). Now, we will write the formal definition of a recurrence relation. Definition 7.1 Arecurrence relationfor the sequence π0, π1, π2, β¦ Is an equation that relatesππto its predecessorsπ0,π1, β¦ ππβ1 Initial conditions for the sequenceπ0, π1, β¦are explicitly given values for a finite number of the terms of the sequence
For example, the Fibonacci sequence is defined by the recurrence relation ππ= ππβ1+ ππβ2π β₯3 With initial conditionsπ1= 1,π2= 1 We can form this sequence both recursively (on the left) and iteratively (on the right). We can now have some definition. The first is a linear homogeneous recurrence relation and the second is for the non-homogeneous case. Definition 7.2 Alinear homogeneous recurrence relationof orderπwith constant coefficients is a recurrence relation of the form ππ= π1ππβ1+ π2ππβ2+ β― + ππππβπ,ππβ 0 Notice that a linear homogeneous recurrence relation of orderπwith constant coefficients, together with theπinitial conditions π0= πΆ0, π1= πΆ1, β¦ , ππβ1= πΆπβ1 Uniquely defines a sequenceπ0,π1,β¦. Similarly, we have non-homogeneous relations: Definition 7.3 Alinear non-homogeneous recurrence relationof orderπwith constant coefficients is a recurrence relation of the form ππ= π1ππβ1+ π2ππβ2+ β― + ππππβπ+ π(π),ππβ 0 In other words, a non-homogenous recurrence has extra terms which are not related to previous terms. Ifπ(π)= 0then it is homogeneous. In this module, we only look at the homogeneous cases and mostly the second order cases. This is because this is a computer science course and to solve generalised cases involve more maths. The most important takeaway is to understand what a recurrence relation is and how we can produce the sequence using recursion. Going back to the (infamous) Fibonacci sequence, the relation ππ= ππβ1+ ππβ2 is an example of a linear homogeneous recurrence relation of order 2. Worked Example: What is the order of the following recurrence relations? Are they homogeneous or non- homogeneous? a)ππ= 11ππβ1β39ππβ2+ 45ππβ3Third order, homogeneous. b)ππ= ππβ1+ 2ππβ2Second order, homogeneous c)π₯π= π₯πβ2Second order, homogeneous
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
d)ππ= ππβ1+ 4First order, non-homogeneous e)ππ= 5ππβ1β4ππβ2+ π2Second order, non-homogeneous. Your turn: What is the order of the following recurrence relations? Are they homogeneous or non- homogeneous? a)ππ= 3ππβ1+ ππβ2+ ππβ4 b)ππ= 5ππβ1β3ππβ2β1 Second Order Linear Homogeneous Recurrence Relations Let ππ= π1ππβ1+ π2ππβ2 Be a second order, linear homogeneous recurrence relation with constant coefficients. Ifπandπare solutions, thenπ= ππ + ππis also a solution of *. Ifπis a root of the characteristic (or auxiliary) equation defined as: π‘2β π1π‘ β π2= 0 Then the sequenceππ,π= 0,1, β¦is a solution. Ifπis the sequence defined by *, π0= πΆ0,π1= πΆ1 Andπ1andπ2are roots of * withπ1β π2, then there exist constantsπandπsuch that ππ= ππ1 π+ ππ2 π This is called thegeneral solution. Given a set of initial conditions, finding the values ofπandπresult in theparticular solution. Worked Example: What is the general and particular solutions to the recurrence relationππ= 7ππβ1β12ππβ2with initial conditionsπ1= 1andπ2= 4? Rearranging gives: Therefore, the characteristic solution is: π‘2β7π‘ + 12 = 0 This can be factorised as (π‘ β4)(π‘ β3)= 0 And has solutionsπ‘= 4andπ‘= 3. Therefore, the general solution is ππ= π Γ 4π+ π Γ 3π Substituting the first two values inπ1= 1andπ2= 4gives π1: 1 = 4π + 3π
π2: 4 = 16π + 9π Solving these simultaneous equations gives the solutionπ=1 4andπ= 0. Therefore, the particular solution isππ=1 4Γ 4π+ 0 Γ 3π=1 4Γ 4πorππ= 4πβ1 Your turn: What is the general and particular solutions to the recurrence relationππ= 7ππβ1β12ππβ2with initial conditionsπ1= 1andπ2= 3 Application: Fibonacci and Lucas Recurrence Relations The relation ππ= ππβ1+ ππβ2 Can be rewritten asππβ ππβ1β ππβ2,π β₯ 3and initial conditionsπ1= 1,π2= 1. We begin by using the quadratic formula to solve π‘2β π‘ β1 = 0 The solution of this quadratic isπ‘=1Β±β5 2 π‘=1 Β±β5 2 Thus, the general solution is: ππ= π(1 +β5 2) π + π(1 ββ5 2) π To find the particular solution: ππ= π(1 +β5 2) π + π(1 ββ5 2) π To satisfy the initial conditions, we must have π(1 +β5 2)+ π(1 ββ5 2)= 1 And π(1 +β5 2) 2 + π(1 ββ5 2) 2 = 1 ππ= π(1 +β5 2) π + π(1 ββ5 2) π Using the initial conditions and the first term of the sequence, we have:
π1= 1 β π(1 +β5 2)+ π(1 ββ5 2)= 1 Which results in: π(1 + β5)+ π(1 β β5)= 2 Taking the second term in the sequence. π2= 1 β π(1 +β5 2) 2 + π(1 ββ5 2) 2 = 1 Which results in: π(3 + β5)+ π(3 β β5)= 2 We then have the system of equations: π(1 + β5)+ π(1 β β5)= 2 π(3 + β5)+ π(3 β β5)= 2 Which can be solved simultaneously forπandπ, to obtain π=1 β5,π = β 1 β5 Therefore, the particular solution is: ππ=1 β5(1 +β5 2) π β1 β5(1 ββ5 2) π Surprisingly, even thoughππis an integer, the formula involves the irrational numberβ5. The number1+β5 2which is called the golden ratio,π=1+β5 2and has the property1 π= π β 1. The Fibonacci sequence is fascinating and has many interesting properties. The first eight Fibonacci numbers is then 1,1,2,3,5,8,13,21,β¦ If we sum these, we get 1,2,4,7,12,20,ππ‘π These look like they are one less than term two ahead, I,e, π1+ π2+ β― + ππ= ππ+2β1 We can prove this by mathematical induction: Letπ(π): π1+ π2+ β― + ππ= ππ+2β1 Then, π1= 1,π3β1 = 2 β 1 = 1 So,π(1)is true. Assumingπ(π): π1+ π2+ β― + ππ= ππ+2β1is true, then π(π+ 1): π1+ π2+ β― + ππ+ ππ+1= ππ+3β1
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Now, asπ(π)is true ππ+2β1 + ππ+1= ππ+3β1 Asππ+1+ ππ+2= ππ+3by definition. Thereforeπ(π + 1)is true. Therefore, by mathematical induction, as π(π)β π(π + 1)is true andπ(1)is true, then π1+ π2+ β― + ππ= ππ+2β1 Extension Topic: General Homogeneous Recurrence Relations This section is not examinable. So far, we have only considered recurrence relations whose characteristic equation results in two distinct solutions. Sometimes when solving a quadratic equation, you might get a repeated solution or no real solution. We will consider here those types of recurrence relations. If we have repeated (equal) roots of the characteristic equation, we have to make a slight modification as can be seen in the following example. To solve the recurrence relationππ= 6ππβ1β9π₯πβ2, we first look at the characteristic equationπ2β 6π + 9 = 0which factorises to(π β3)(π β3)= 0with the solutionπ= 3. Therefore, the general solution would look likeππ= π΄ Γ 3πwhere normally we would expect two solutions for a second order recurrence relation. If we consider the expressionππ= π Γ 3π, thenππβ1=(π β1)Γ 3πβ1andππβ2= (π β2)Γ 3πβ2. Substituting these into the recurrence relation, we have: πΏπ»π= π Γ 3π π π»π= 6(π β1)Γ 3πβ1+ 18 Γ 3πβ2 = 6π Γ 3πβ1β9π Γ 3πβ2β6 Γ 3πβ1+ 18 Γ 3πβ2 = 2π Γ 3πβ πΓ 3π= π Γ 3π= πΏπ»π Therefore, the left- and right-hand sides are equal andπΓ 3πis also a solution to the recurrence relation. The general solution is then ππ= π΄ Γ 3π+ π΅π Γ 3π In general, we can show that if there is only one root (in reality two repeated roots)πof the auxiliary equation, the general equation is then: ππ= π΄ππ+ π΅πππ=(π΄+ π΅π)ππ In our example above, the general solution isππ=(π΄+ π΅π)3π. We will use a second example to help illustrate how to solve recurrence relations when there are no real roots. If we consider finding the general solutionππ= β3ππβ2, π β₯ 2and then the particular solution when π0= 1andπ1= 2. The characteristic equation isπ‘2= β4which has complex solutionsπ= 2πandπ= β2π. The general solution is then: ππ= π΄(β2)ππ+ π΅(2π)π Now, asπ0= 1andπ1= 2,π0= π΄ + π΅ = 1andπ1= β2ππ΄ + 2ππ΅ = 2 β βπ΄ + π = βπ. Solving these simultaneously forπ΄andπ΅gives: π΄=1 2(1 + π) π΅=1 2(1 β π)
The particular solution isππ=1 2(1 + π)(β2π)π+1 2(1 β π)(2π)π. Extension Topic: Non-homogeneous Recurrence Relations Non-homogeneous recurrence relations are more difficult to generally solve than that of homogeneous relations. There is no completely systematic way to solve these but sometimes a form can be suggested. For example, taking the recurrence relationππ+ 3ππβ1+ 2ππβ2= π2. Firstly, we take the homogeneous part of the relationππ+ 3ππβ1+ 2ππβ2= 0whose characteristic equation is π₯2+ 3π₯ + 2 = 0 Factorising gives: (π₯+ 2)(π₯+ 1)= 0 Giving solutionsπ₯= β1andπ₯= β2which are the roots of the characteristic equation. This gives us the solution to the homogeneous part in the form ππ= π΄(β1)π+ π΅(β2)π This is called thegeneral solution. As the righthand side is a quadratic, then we can form theparticular solutionas ππ= πΆπ2+ π·π + πΈ Where we need to find whatπΆ, π·andπΈare to obtain the particular solution. We may do this by substituting this into our recurrence relation withπ= π, π β 1, π β 2: (πΆπ2+ π·π + πΈ)+ 3(πΆ(π β1)2+ π·(π β1)+ πΈ)+ 2(πΆ(π β2)+ π·(π β2)+ πΈ)= π2 Simplifying we get: 6πΆπ2+(β14πΆ + 6π·)π+(11πΆ β 7π· + 6πΈ)= 1π2+ 0π + 0 We can then equate coefficients: 6πΆ = 1, = 14πΆ + 6π· = 0, 11πΆ β 7π· + 6πΈ = 0 Solving these three equations, we getπΆ=1 6, π· = 14 36andπΈ= 32/216. Hence the general solution is: ππ=1 6π2+14 36π+32 216+ π΄(β1)π+ π΅(β2)π And finally,π΄andπ΅may be found if the initial conditions are known, as before.
Recursion in Python In this section, we will look at the programming equivalent to recurrence relation which is recursion. At its simplest definition, recursion recalls a function within the same function. For example, if we take the factorial of a number, which is defined as: π! = 1 Γ 2 Γ 3 Γ β¦ Γ(π β1)Γ π This can be expressed as: π! = π Γ(π β1)! Where1! = 1. This can then be expressed as a recursive function: def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) If we call this function, say as: n = factorial(4) we can then trace the function through. In our first time through the function, we will then call 4 * factorial(3) Then, we will need to work out what factorial(3) is. To find factorial(3) we go into the function again which leads to the line: 3 * factorial(2) Repeating this process we find 2 * factorial(1) Finallyfactorial(1)returns 1. So, then we go back through the tree: 2 * 1 Then going back a step again 3 * 2 And back again, 4 * 3 And so, finally,factorial(4)returns 12 as its result.
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Another call tree which shows a similar process is: Frequently, we can rewrite loops as recursive routines and vice versa. However, not all recursive routines can be written iteratively (in a loop). One major disadvantage to recursion is it can lead to stack errors. Each time the function is called, a new instance of that function is created and then put onto the call stack.
We therefore must ensure that we do not use recursive functions on large input variables. Another example of a recursive function is Which will result in the output:
By looking at the output, we can see the number is increasing by one each time through. But unlike the factorial function there are problems with this function. The printout keeps going until the program crashes. You might like to think about why this might happen. The algorithm firstly prints the value of x, then increments this by one and then calls a new copy of itself with the new value of x. This function can never terminate as there is no base condition. Before the function terminates, another function call is made. This is an example of an infinite function. In principle, infinite recursion is possible but not in practice. Each function call is implemented using the system stack. A stack frame is created with space for parameters and local variables and is pushed onto the stack. Each recursive call to the function then pushes another stack frame onto the stack. Therefore, the stack frame increases and will grow large. Eventually the stack will grow too large, and the program will crash. Python sets an upper limit on the number of recursive calls to a single function (which is called the depth of recursion) so that this cannot happen. So, the problem with the program careless is that it contains no statement that tells Python when to stop making recursive calls to itself. It simply counts up from the starting value of x without stopping. We will need to provide it with more information. A possible improvement is the following: This though will still not stop. We provided some information about when to stop but this is not acted upon and is not used. We need an if statement that catches the stopping case (which as mentioned is called the base case) and it makes sure that there is no recursive call to the function when that case occurs. So, we can form the following code:
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
This definition ensures that there will eventually be a situation where no recursive call is made. The program can still crash if Pythonβs recursion limit is exceeded though. That depends on the start and stop values that are passed as parameters. Instead of using an if statement for the base case, we may use an if statement for the continuation case, such as: This will again result in a situation where no recursive call is made. Mathematics Questions 1)For the following recurrence relations find the order and specify whether it is homogeneous or not. a.ππ= 7ππβ1β3ππβ2 b.ππ= 2ππβ3 c.ππ= πππβ1+ ππβ2 d.ππ= ππβ1+ ππβ2+ π 2)What is the difference between the general solution and particular solution for a recurrence relation? 3)For the following recurrence relations, find a closed form solution (i.e. not using recursion) by solving the characteristic equation. UseWolfram|Alpha Widgets: "Simultaneous Equations Solver" - Free Mathematics Widget (wolframalpha.com)to help you solve the resulting simultaneous equations. a)ππ= 2ππβ1+ 3ππβ2,π0= 1, π1= 2 b)ππ= 4ππβ1β3ππβ2π0= 2, π1= 5 4)Use an appropriate problem-solving strategy (such as HTTLAP from the first lecture notes) to think of solutions to the Tower of Hanoi problem for four pegs.
Programming Questions General β’A recursive function will have one or more parameters that are used to pass information into the function β’The value(s) of the parameter(s) will be used to control whether or not the function calls itself recursively (with modified parameter values) When writing a recursive function Firstidentify and code the base case(the stopping case) β’All recursive functions need a base case β some have more than one β’The base case is the parameter value (or set of parameter values) for which working out the result is a trivial task β’Example 1 Suppose we're writing a functionadd_allto add up all the numbers between 1 and n. If the parameter passed as n is the number 1 the function simply returns 1 β’Example 2 Suppose we're writing a functionmax_into find the maximum number in a list of numbers. If it is passed as a parameter a list containingjust onenumber that number must be the maximum in the list. So if the length of the list is 1 our function returns the only number in the list Thenidentify and code the recursive case(the case that makes progress towards a result) β’All recursive functions need a recursive case β some have more than one β’Any parameter value for which the result cannot be found trivially must be processed using recursion β’The recursive case is the one in which the function calls itself. β’It is needed to make progress towards a result when that result cannot be obtained in a single step β’Each recursion involves a call to the function with parameters that are closer in value to those that match the base case β’The function returns the result of a calculation based upon the result it gets back from the recursive call β’Example 1 Suppose we're writing a functionadd_allto add up all the numbers between 1 and n. If the parameter passed as n is the number 5 the function adds 5 to the result of adding up all the numbers from 1 to 4 β’Example 2 Suppose we're writing a functionmax_into find the maximum number in a list of numbers. If it is passed as a parameter a list containingseveral numbersthe result is the larger of the first number in the list and the maximum of thise inthe rest of the list
Example 1add_all def add_all (n) : # calculates the sum of all the numbers between 1 and n if n == 1 :# base case return 1 else:# recursive case total = n + add_all (n-1) return total Note that whenadd_allcalls itself recursively it passes in the parameter n-1, which is 1 less than the n it received. Thus, each recursive call makes progress towards the base case Example 2max_in def max_in (numlist) : # Finds the maximum number in a list of numbers if len(numlist) == 1 :# base case return numlist[0] else:# recursive case if numlist[0] > max_in (numlist[1:]) : return numlist[0] else : return max_in (numlist[1:]) Note that whenmax_incalls itself recursively it passes in the parameternumlist[1:]which is one element shorter than the listnumlistthat it received. Thus, each recursive call makes progress towards the base case Example 2amax_inbut a little more efficient (and hopefully easier to read) def max_in (numlist) : head = numlist[0]# first number in the list tail = numlist[1:]# rest of the list if tail == [] :# base case (rest of list is empty) return head else:# recursive case max_tail = max_in(tail) if head > max_tail : return head else : return max_tail
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
Use recursionto solve each of the problems below 1.Write a function that takes a positive whole number as its parameter and returns the factorial of that number. Hint: factorial(1) is 1, factorial(n) is n*(factorial(n-1)), for all n greater than or equal to 2 2.Write a function smallest_pos that takes a list of numbers as its parameter and returns the smallest positive number in the list. Hint: This is like max_in, but alittlemore complex, because negative numbers are not counted). No need to worry about what to do with a list that does not contain a positive number 3.Write a function reverse, that takes a list as its parameter and returns the reversed version of the list. Hint: A list containing a single element does not need to be reversed. Also, reversing the list involves placing its headafterits reversed tail Note: Python's append method will not work on lists created by unwinding from recursionj What do you have to change to make reverse work with strings as well? 4.Write a function multiply that takes two non-negative whole numbers a and b as parameters and multiplies them together by repeated addition. Hint: if b is 0 the function will return 0. If b is greater than 0 it will returna + multiply(a, b-1) What do you have to change to make this function work with negative whole numbers as well as non-negative? 5.Write a functiongcdthat takes two positive whole numbers a and b as parameters and returns their greatest common divisor. Hint: use Euclid's method for finding the gcd. The base case is when a is equal to b. 6.Write a functionfirst_nthat takes a single positive whole number, n, as its parameter and returns a list containing the first n positive numbers in ascending order. What do you have to change to make this function return the list of the first n positive whole numbers in descendingorder? 7.Write a function power that takes two positive whole numbers a and b as parameters and returns a raised to the power b, calculated by repeated multiplication. 8.Write a function binary that takes a non-negative whole number as its parameter and creates a string of zeros and ones representing that number in binary 9.Write a function is_palindrome that takes a character string as its parameter and returns True if that string is a palindrome (a string that reads the same backwards as it does forwards) and False if it is not. Hint: An empty string is a palindrome, as is a string containing just one character. A longer string is a palindrome if its first and last characters are the same and the rest of the string is also a palindrome. What do you have to change to make this function capable of testing whetherlistsare palindromes? 10.Referring to the Towerβs of Hanoi problem from the mathematics questions, think of an appropriate solution coded in Python using recursion to solve the puzzle. Once complete, test the solutions using your hand solutions from earlier on.