Start learning free

LESSON 128 OF 410 · LOOPS & CONDITIONALS

Even Numbers From List: Buggy Code in Python (Time Complexity: O(n))

Practice Read the full explanation

Inside the code editor we've tried to write a function that takes a list nums as argument and prints to the console the even numbers from that list.

So when we called print_even_numbers([2, 1, 0, 4, 3]), we expected our code to print:

2
0
4

but it seems like we made some mistakes because when we run our code, it prints:

even
even

Assignment:

Your task is to fix our function such that it prints the even numbers from the list.

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · LOOPS & CONDITIONALS

    Buggy Code Print Even Numbers in Python, explained

    Understanding the Problem

    The core challenge here is to correctly identify and print the even numbers from a given list. The significance of this problem lies in its simplicity and its frequent use in various applications, such as filtering data or processing lists based on specific conditions. A common pitfall is misunderstanding the condition for even numbers or incorrectly handling the list iteration.

    Approach

    To solve this problem, we need to iterate through the list and check each number to see if it is even. A number is even if it is divisible by 2 with no remainder (i.e., num % 2 == 0). The initial naive solution might involve incorrect logic or syntax errors, as seen in the provided code.

    Naive Solution

    The naive solution might look something like this:

    def print_even_numbers(nums):
        for num in nums:
            if num % 2 == 0:
                print("even")
    

    This code incorrectly prints the string "even" instead of the actual even numbers. The logic for checking even numbers is correct, but the print statement is wrong.

    Optimized Solution

    The optimized solution involves simply printing the number itself if it is even:

    def print_even_numbers(nums):
        for num in nums:
            if num % 2 == 0:
                print(num)
    

    This solution correctly prints each even number from the list.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Iterate through each number in the list nums.
    2. Check if the current number is even by using the modulus operator (%).
    3. If the number is even, print it.

    Code Implementation

    def print_even_numbers(nums):
        # Iterate through each number in the list
        for num in nums:
            # Check if the number is even
            if num % 2 == 0:
                # Print the even number
                print(num)
    
    # Example usage
    print_even_numbers([2, 1, 0, 4, 3])
    

    Complexity Analysis

    The time complexity of this solution is O(n), where n is the number of elements in the list. This is because we need to check each element once. The space complexity is O(1) as we are not using any additional space that scales with the input size.

    Edge Cases

    Consider the following edge cases:

    • An empty list: The function should not print anything.
    • A list with no even numbers: The function should not print anything.
    • A list with all even numbers: The function should print all numbers.

    Examples:

    print_even_numbers([])  # No output
    print_even_numbers([1, 3, 5])  # No output
    print_even_numbers([2, 4, 6])  # Output: 2 4 6
    

    Testing

    To test the solution comprehensively, use a variety of test cases:

    def test_print_even_numbers():
        import io
        import sys
    
        # Helper function to capture print output
        def capture_output(func, *args, **kwargs):
            old_stdout = sys.stdout
            new_stdout = io.StringIO()
            sys.stdout = new_stdout
            func(*args, **kwargs)
            sys.stdout = old_stdout
            return new_stdout.getvalue().strip()
    
        # Test cases
        assert capture_output(print_even_numbers, [2, 1, 0, 4, 3]) == "2\n0\n4"
        assert capture_output(print_even_numbers, []) == ""
        assert capture_output(print_even_numbers, [1, 3, 5]) == ""
        assert capture_output(print_even_numbers, [2, 4, 6]) == "2\n4\n6"
    
        print("All tests passed.")
    
    # Run tests
    test_print_even_numbers()
    

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Understand the problem requirements and constraints thoroughly.
    • Break down the problem into smaller, manageable steps.
    • Start with a simple solution and then optimize it.
    • Test your solution with various edge cases to ensure its robustness.

    To improve problem-solving skills, practice regularly, study different algorithms, and solve similar problems on coding challenge platforms.

    Conclusion

    In this blog post, we discussed how to fix a function that prints even numbers from a list. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong programming skills. Keep practicing and exploring further to enhance your problem-solving abilities.

    Additional Resources

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free