Write a function using iteration to print numbers from 1 to a given number, then extend it to print only even numbers, and finally modify it to accept a step size.

Medium
9 years ago

Write a function that uses iteration to print all numbers from 1 to a given number. For example, if the input is 5, the function should print: 1, 2, 3, 4, 5. Now, extend this function to print only the even numbers within that range. For instance, if the input is 10, the output should be: 2, 4, 6, 8, 10. Finally, modify the function to accept a second argument, which represents the step size. Using iteration, print numbers starting from 1 up to the given number, incrementing by the step size. As an example, given the number 15 and a step size of 3, the expected output is: 1, 4, 7, 10, 13. Be sure to handle edge cases and invalid inputs appropriately.

Sample Answer

Iteration Problems in Python

This document addresses a series of iteration-based coding challenges in Python, progressing from basic printing of numbers to handling step sizes and edge cases.

1. Printing Numbers from 1 to N

Naive Solution

def print_numbers(n):
    """Prints numbers from 1 to n using iteration."""
    if not isinstance(n, int) or n <= 0:
        print("Invalid input. Please provide a positive integer.")
        return
    for i in range(1, n + 1):
        print(i, end=" ")
    print()

# Example usage
print_numbers(5)  # Output: 1 2 3 4 5

This is the straightforward solution, using a simple for loop to iterate from 1 to n (inclusive) and printing each number.

Big O Analysis

  • Time Complexity: O(n), where n is the input number. The loop iterates n times.
  • Space Complexity: O(1), as it uses a fixed amount of space regardless of the input.

Edge Cases

  • Invalid Input: The function checks if the input is a positive integer. If not, it prints an error message and returns.

2. Printing Even Numbers from 1 to N

Naive Solution

def print_even_numbers(n):
    """Prints even numbers from 1 to n using iteration."""
    if not isinstance(n, int) or n <= 0:
        print("Invalid input. Please provide a positive integer.")
        return
    for i in range(2, n + 1, 2):
        print(i, end=" ")
    print()

# Example usage
print_even_numbers(10)  # Output: 2 4 6 8 10

This improved solution starts the loop at 2 and increments by 2, ensuring that only even numbers are printed. This reduces the number of iterations.

Big O Analysis

  • Time Complexity: O(n/2) which simplifies to O(n), where n is the input number. Although it iterates only through even numbers, the complexity is still linear with respect to n.
  • Space Complexity: O(1), as it uses a fixed amount of space.

Edge Cases

  • Invalid Input: The function checks for non-positive integer inputs.

3. Printing Numbers with a Step Size

Naive Solution

def print_numbers_with_step(n, step):
    """Prints numbers from 1 to n with a given step size using iteration."""
    if not isinstance(n, int) or n <= 0 or not isinstance(step, int) or step <= 0:
        print("Invalid input. Please provide positive integers for n and step.")
        return
    
    for i in range(1, n + 1, step):
        print(i, end=" ")
    print()

# Example usage
print_numbers_with_step(15, 3)  # Output: 1 4 7 10 13

This function introduces a step size to the iteration. It checks for invalid inputs for both n and step to ensure they are positive integers.

Big O Analysis

  • Time Complexity: O(n/step), which can be considered O(n) in the worst case (when step is small).
  • Space Complexity: O(1), as it uses a fixed amount of space.

Edge Cases

  • Invalid Input: Checks for non-positive integers for both n and step.
  • Step Size: If the step size is larger than n, it will still execute correctly, printing only the starting number (1).

Conclusion

These examples illustrate how iteration can be used to solve simple numerical problems with increasing complexity. Each function includes input validation and considers potential edge cases to ensure robustness.