# 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)
Method 1: Using a loop
- 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
- 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
- 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.
0 Comments:
Post a Comment