oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/python/generators.txt
1.4 KiB, 1 run
created by r1870400018:12030, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | from typing import Generator, Iterator, Iterable |
| 2 | import itertools |
| 3 | |
| 4 | |
| 5 | def fibonacci() -> Generator[int, None, None]: |
| 6 | a, b = 0, 1 |
| 7 | while True: |
| 8 | yield a |
| 9 | a, b = b, a + b |
| 10 | |
| 11 | |
| 12 | def primes() -> Generator[int, None, None]: |
| 13 | """Sieve of Eratosthenes, unbounded.""" |
| 14 | composites = {} |
| 15 | n = 2 |
| 16 | while True: |
| 17 | if n not in composites: |
| 18 | yield n |
| 19 | composites[n * n] = [n] |
| 20 | else: |
| 21 | for prime in composites[n]: |
| 22 | composites.setdefault(prime + n, []).append(prime) |
| 23 | del composites[n] |
| 24 | n += 1 |
| 25 | |
| 26 | |
| 27 | def take(n: int, iterable: Iterable) -> list: |
| 28 | return list(itertools.islice(iterable, n)) |
| 29 | |
| 30 | |
| 31 | def windowed(iterable: Iterable, size: int) -> Generator: |
| 32 | it = iter(iterable) |
| 33 | window = [] |
| 34 | for _ in range(size): |
| 35 | try: |
| 36 | window.append(next(it)) |
| 37 | except StopIteration: |
| 38 | return |
| 39 | yield tuple(window) |
| 40 | for item in it: |
| 41 | window.pop(0) |
| 42 | window.append(item) |
| 43 | yield tuple(window) |
| 44 | |
| 45 | |
| 46 | def batched(iterable: Iterable, n: int) -> Generator: |
| 47 | it = iter(iterable) |
| 48 | while True: |
| 49 | batch = list(itertools.islice(it, n)) |
| 50 | if not batch: |
| 51 | return |
| 52 | yield batch |
| 53 | |
| 54 | |
| 55 | if __name__ == '__main__': |
| 56 | print(f"first 10 fibs: {take(10, fibonacci())}") |
| 57 | print(f"first 10 primes: {take(10, primes())}") |
| 58 | print(f"windows: {list(windowed(range(6), 3))}") |
| 59 | print(f"batches: {list(batched(range(10), 3))}") |