Generators & classes
Generators, a vector class with operators, and coroutines driven by hand.
programmingDownload (ZIP)Source on GitHub
Preview
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
from itertools import islice
list(islice(fib(), 20))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
class Vec:
def __init__(self, *xs): self.xs = xs
def __add__(self, o): return Vec(*(a + b for a, b in zip(self.xs, o.xs)))
def __mul__(self, k): return Vec(*(k * a for a in self.xs))
__rmul__ = __mul__
def __repr__(self): return f"Vec{self.xs}"
3 * Vec(1, 2) + Vec(0, 1)Vec(3, 7)
# Coroutines, driven by hand
async def square(x):
return x * x
async def main():
total = 0
for i in range(5):
total += await square(i)
return total
c = main()
try:
c.send(None)
except StopIteration as e:
print('result', e.value)result 30
Files
main.ipynb(1644 bytes)