63 lines
1.2 KiB
Python
63 lines
1.2 KiB
Python
import time
|
|
|
|
def my_generator():
|
|
yield 3
|
|
yield 2
|
|
yield 1
|
|
|
|
for value in my_generator():
|
|
print(value)
|
|
|
|
|
|
# Using next() to manually iterate through the generator
|
|
g = my_generator()
|
|
print(next(g)) # Output: 1
|
|
print(next(g)) # Output: 2
|
|
print(next(g)) # Output: 3
|
|
|
|
print(sum(my_generator())) # Output: 6
|
|
print(sorted(my_generator())) # Output: [1, 2, 3]
|
|
|
|
def countdown(n):
|
|
while n > 0:
|
|
yield n
|
|
n -= 1
|
|
|
|
for number in countdown(4):
|
|
print(number)
|
|
time.sleep(1) # Pause for 1 second between numbers
|
|
|
|
# Example of a generator function to yield first n numbers
|
|
def firstn(n):
|
|
num = 0
|
|
while num < n:
|
|
yield num
|
|
num += 1
|
|
|
|
# calling firstn():
|
|
for number in firstn(10):
|
|
print(number)
|
|
|
|
|
|
print(sum(firstn(100))) # Output: 4950
|
|
|
|
|
|
# Example of a generator expression
|
|
squared = (x * x for x in range(10))
|
|
for num in squared:
|
|
print(num)
|
|
|
|
# Fibonacci sequence generator
|
|
def fibonacci(n):
|
|
a, b = 0, 1
|
|
for _ in range(n):
|
|
yield a
|
|
a, b = b, a + b
|
|
|
|
for num in fibonacci(30):
|
|
print(num)
|
|
|
|
print(list(fibonacci(30))) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
|
|
|
|
|
|