# Python pattern challenge - Day 3

### # Method 1: Using a loop

def print_sequence_loop(n):

for i in range(n+1):

print(f"{i}{'*' * i}")

### # Method 2: Using list comprehension

def print_sequence_list_comprehension(n):

sequence = [f"{i}{'*' * i}" for i in range(n+1)]

print('\n'.join(sequence))

### # Method 3: Using a generator function

def generate_sequence(n):

for i in range(n+1):

yield f"{i}{'*' * i}"

def print_sequence_generator(n):

sequence = generate_sequence(n)

for item in sequence:

print(item)

# Testing the functions

n = 5

print("Using loop:")

print_sequence_loop(n)

print("\nUsing list comprehension:")

print_sequence_list_comprehension(n)

print("\nUsing generator function:")

print_sequence_generator(n)

Let's break down each part of the code:

### Method 1: Using a loop

This method uses a loop to generate and print each element of the sequence.

def print_sequence_loop(n):
for i in range(n+1):
print(f"{i}{'*' * i}")
• print_sequence_loop is a function that takes an integer n as input.
• It iterates over the range from 0 to n (inclusive) using a for loop.
• Inside the loop, it prints a string composed of the current number i followed by a number of asterisks (*) corresponding to the value of i.

### Method 2: Using list comprehension

This method uses list comprehension to generate the sequence and then prints it.

def print_sequence_list_comprehension(n):
sequence = [f"{i}{'*' * i}" for i in range(n+1)]
print('\n'.join(sequence))
• print_sequence_list_comprehension is a function that takes an integer n as input.
• It uses list comprehension to generate a list where each element is a string composed of the current number i followed by a number of asterisks (*) corresponding to the value of i.
• It then joins the elements of the list with newline characters ('\n') and prints the resulting string.

### Method 3: Using a generator function

This method uses a generator function to lazily generate the sequence, and then prints it.

def generate_sequence(n):
for i in range(n+1):
yield f"{i}{'*' * i}"

def print_sequence_generator(n):
sequence = generate_sequence(n)
for item in sequence:
print(item)
• generate_sequence is a generator function that yields each element of the sequence lazily. It takes an integer n as input.
• Inside the function, it iterates over the range from 0 to n (inclusive) using a for loop, yielding a string composed of the current number i followed by a number of asterisks (*) corresponding to the value of i.
• print_sequence_generator is a function that takes an integer n as input.
• It creates a generator object sequence by calling generate_sequence(n).
• It then iterates over the elements of the generator using a for loop, printing each element.