A2 Theory W8 Flashcards

1
Q

Briefly describe the concept of recursion in Computer Science by

Providing a definition of recursion in your own words;

Providing an example and explaining how it works;

Explaining what is the base case and recursive case of the example given.

A

Recursion in computer science is a programming concept where a function or method calls itself to solve a problem, breaking it down into smaller and smaller problems until the base case has been reached. It’s a problem solving approach that relies on solving simpler subproblems of the same problem until the lowest possible problem has been solved (base case).

Example: calculating the factorial of a number using recursion
- when you call ‘factorial(n)’ which is a function, with a value of ‘n’, the function checks if ‘n’ is either 0 or 1, if it is then it returns 1 (base case)
- if ‘n’ is greater than 1, it entres the recursive case and calculates ‘n * factorial(n-1) by calling the factorial functiona on itself with a smaller value ‘n-1’
- this process continues until n becomes 1 and the base case is met
- after this all the recursive calls start returning values and the final result os the product of all the values returned by recursive calls which effectively gives you the factorial of n

In this example, the base case is when ‘n’ is 0 or 1 and the recursive case is when ‘n’ is greater than 1. The recursion breaks down the factorial into smaller sub problems until it reachers the base case.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Contrast the operation of recursion and iteration in Computer Science. Analyze the advantages and disadvantages of using recursion over iteration in Computer Science. Provide an example and explain the reasoning behind your answers.

A

Recursion and iteration are both fundamental programming concepts used to solve problems in computer science.

Recursion:
Recursion is a technique where a function calls itself to solve a problem by breaking it down into smaller sub-problems. It relies on a base case that serves as the termination condition.

Advantages of recusrion:
- elagance and readibility: recursive solutions can be more elegant and readable, especially for problems that have a naturally recursive nature
- simplifies complex problems: recursion can simplify the solution for complex problems, making the code easier to understand
- natural for certain problems: some problems, like those involving hieracherial data strucutues like trees are nautrall suited to recursion

Disadvantage of recursion:
- stack overhead: each recursive call adds a new function call to the call stack, which can lead to stack overflow errors or infinite recusrion
- performance: recusrive solutions can less efficient in terms of memory usage and execution time compared to iterative solution, as each function call consumes memory and incurs function call overhead
- difficult to debug: recursive code can be more challenging to debig due to stack trace and multiple recursive calls
- simple does not always mean better: recursion can be a simple and elegant approach but that does not always mean a better approach to solving all problems and things can be oversimplified making them harder to understand

Iteration:
Iteration involves using loops to repreatedly execute a set of instructions untila specific condition is met. It is more straightforward and efficient way to solve problems.

Advantages of iteration:
- efficiency: iterative solutions often use less memory and excute faster than resurcsive because they dont involve the overhead of function calls
- predictable performance: iteration typically has a more predictable performance profile, making it suitable for cases where efficiency is ciritcal
- control: with iteration, you have more control over the execution flow and can optimize it for specific situations

Disadvantage of iteration:
- complexity for some problems: some problems may require complex loop structures, making the code less readable
- not suitable for all cases: iteration may not be the best choice for peoblems with a natural recursive structure, as implementing then iteratively can be convuluded

Example: Calculating fibonacci numbers
Recursively:
- check for base case with if/elif
- else: return fib_recursive(n-1) + fib_recursive(n-2)
Iteratively:
- check for base case with if/elif
- use for loop for range(2, n+1): prev, current = current, prev + current
- return current

Reasoning: in this example, both solutions can calculate fibonacci numbers. The recursive solution is more concise and reflects the mathematical definition of fibonacci sequence. However, can suffer from performance issues with large values of ‘n’ due to excessive finction calls and stack overflow.
The iterative solution, while less elegant, is more efficient and suitable for larger values of ‘n’.

In summary, the choice between recusrion and iteration depends on the problems nature, readibility, and performance requirements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can a recursive function be reimplemented by means of iteration? If yes, how? Give an example.

A

Yes, a recursive function can typically be reimplemented using iteration but not all the time. This process would involve replacing the recursive calls with either for loop or while loop and managing a stack or variables to keep track of the state. It would also require the implementation of the __next__ function which allows the iterator to move onto to the next iterable.

Example: calculating fibonacci numbers
Recursive function:
- if/elif statement to check for base case
- else: return fib_recurs(n-1) + fib_recurs(n-2)

Iterative implementation:
- if/elif to check for base case
- else: prev, current = 0,1
- for loop in range(2, n+1): prev, current = current, prev + current
- return current

Iterative version avoids overhead of function calls and recursion stack, making it more efficient especially when dealing with large values of ‘n’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can an iterative function be reimplemented by means of recursion? If yes, how? Give an example.

A

Yes, an iterative function can be reimplemented using recursion. This often means following a different approach compared to the iterative solution.

The process of converting an iterative function to a recursive one is to stimulate the loops behaviour using recusrive calls and possibly an additonal parametre to maintain state.

Example: facorial function

The original iterative function calculates the facortial using a for loop where as the recursive version uses a base case and recusrive calls

Recusrive version:
- if n is 0 or 1, it returns 1, as the factorial of 0 and 1 is 1. Where n is the input number.
- for ‘n’ greater than 1, it recursively calls ‘factorial_recursive(n-1)’ and multiplies the result by ‘n’ to compute the factorial

The recursive version essentially simulates the loop in the iterative function by using repeated function calls and decreasing ‘n’ until it reaches the base case.

It’s important to note while reimplementation with recusrion is possible, it may not always be the best choice, especially when dealing with larger input size and functions which are designed to be iterative.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Briefly describe the concept of tail recursion by

Providing an example and explaining how it works;

Describing how tail recursion works and how it differs from regular recursion.

A

Tail recursion is a specific form of recursion in which the recursive call is the last operation performed within a function before returning the result. In other words, in tail rec. fucntion, there are no pending operations to be performed after the recursive call returns its result

Example: Factorial tail recursion
- the factorial_tail_recursion fucntion takes two arguments, ‘n’(the input number for which to calculate the factorial) and the ‘acculmulator’(which accumulates the intermediate result)
- it checks if ‘n’ is equal to 0. If ‘n’ is 0, it returns the accumulator, which holds the final result
- if ‘n’ is greater than 0, it recursively calls itself with ‘n-1’ and ‘n * accumulator’. The recursive call updates the ‘accumulator’ with the product of ‘n’ and the current accumulator value.
- this process continues until ‘n’ becomes 0, at which point the final result is returned.

The key chracteristic of tail recursion is that the recusrive call is the last thing that happens in the function before returning a value. This property allow for som programming languages to optimize tail-recursion, making them more memory efficent and potenitally avoiding stack overflow errors.

In contrast the regualr recursion, where there might be addiotional operations after the recursive call, tail recursion has the advantage of efficient memory utilization and is often easier to optimize by compiler or interprator. tail rescursion ensure the function doesnt consume additonal stack space for each recsurive call, making it safer and more efficient for handling deep recusrion. Not all programming languages can support tail recusrion however.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Define the concepts of recursion and iteration and explain how they differ in terms of their properties:

Provide at least one advantage and disadvantage of using recursion compared to iteration,

Provide examples to support your points.

A

Recursion is a programming concept where a function or method calls itself to solve a problem by breaking it down into smaller, more managable sub-problems. It relies on a base case that serves as the termination.

Iteration on the other hand, involves using loops to repeatedly execute a set of insturction until a specific condition is met. It is a more straightforward and efficient way to solve many problems.

Difference in properties:

Termination condition:
- recusrion: relies on a base case to complete termination
- iteration: uses a loop condition as the termination, specifiying when the loop should exit

Control flow:
- recusrion: involves a fucntion calling itself, creating a new stack frame for each call. this can lead to a different execution flow and additnal memory usage
- iteration: follows a linear execution flow within a loop, which can be easier to follow and may use less memory

Memory usage:
- recursion: can consume more memeory due to the creation of a new stack frame for each recusrvie call, can lead to satck overflow
- iteration: typically uses a constant amount of memory because it doesn’t involve the overhead of creating new stack frames

Readability:
- recursion: for some problems with a natural recusrive structure, recusrive solutons an be more elegant and readable
- iteration: for many problems, esepcailly those wihtout a natural recursive structure, iteration can be more straightforward and easier to understand

Advatange and disadvantage of recursion:
advantage:
- elegance and readibility: recursion can result in more elegant a readable code for problems that have a naturally recursive nature
disadvantage:
- stack overhead: each recursive call adds a new function call to the call stack which can lead to stack overflow errors for deep recursion

Example:
Calculating factorial numbers with recursion:
def fac_recusive(n):
if n <= 1: return 1
esle: return n * fac_recursive( n-1)

  • in this example, the recursive solution is elegant and closely mirrors the mathematical definition of the factorial.
  • however, it may not be suitable for large values of ‘n’ due to stack space consumption.

Recusion and iteration are two approaches to solving problems in programming, each with its own set of advantages and disadvantages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly