Day 11: Recursion and Iterators in Python

Day 11: Recursion and Iterators in Python

Topics to Cover:

  • Basics of Recursion and Recursive Functions
  • Iterators, Iterable Objects, and the iter() Function

Introduction to Recursion

Recursion is a method of solving problems where a function calls itself as a subroutine. This allows the function to be repeated several times as it breaks the problem down into smaller, more manageable chunks.

Basic Structure of a Recursive Function:

def recursive_function(parameters):
    if base_condition(parameters):
        return base_case_value
    else:
        return recursive_function(modified_parameters)

Recursive Functions

Example: Calculating the Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

Recursive Function to Calculate Fibonacci Numbers:

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

# Example Usage
print(fibonacci(10))  # Output: 55

Introduction to Iterators

An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Creating an Iterator in Python:
To create an object/class as an iterator, you have to implement the methods __iter__() and __next__() to your object.

Example: Custom Iterator for a Range of Numbers

class MyRange:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.end:
            current = self.current
            self.current += 1
            return current
        else:
            raise StopIteration

# Example Usage
for num in MyRange(1, 10):
    print(num)

Potential Problems to Solve

Problem 1: Recursive Function for Fibonacci Sequence

Task: Write a recursive function to calculate the Fibonacci sequence.

Solution:

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

# Example Usage
print(fibonacci(10))  # Output: 55

Problem 2: Custom Iterator for a Range of Numbers

Task: Implement a custom iterator for a range of numbers.

Solution:

class MyRange:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.end:
            current = self.current
            self.current += 1
            return current
        else:
            raise StopIteration

# Example Usage
for num in MyRange(1, 10):
    print(num)

Conclusion

Understanding recursion and iterators is essential for mastering Python programming. Recursion helps solve problems that can be broken down into smaller subproblems, while iterators allow efficient traversal through elements in a collection.


Stay tuned for Day 12 of the python4ai 30-day series, where we will continue exploring advanced Python topics to enhance our programming skills!

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 480