Program 1
Simple generator
yield values one at a time.
python
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(5):
print(x)Topic 15 of 17
Lazy evaluation with yield, generator expressions, and itertools.
Program 1
yield values one at a time.
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(5):
print(x)Program 1
Like list comp but lazy.
total = sum(x * x for x in range(1, 1_000_001))
print(total)Program 2
Infinite sequence, take what you need.
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
gen = fib()
print([next(gen) for _ in range(10)])Program 1
Group adjacent equal items.
from itertools import groupby
data = "aaabbcaaa"
for key, group in groupby(data):
print(key, len(list(group)))