iters.py
View source code here on GitHub!
Includes
proper_divisors()
__future__.generator_stop
- python.src.lib.iters.abundants(stop: int | None = None) Iterator[int]
Iterate over the abundant numbers.
- python.src.lib.iters.consume(iterator: Iterable[Any], n: int | None = None) None
Advance the iterator n-steps ahead. If n is None, consume entirely. (From itertools recipes)
- python.src.lib.iters.digits(x: int, base: int = 10) Iterator[int]
Iterate over the digits of a number in a given base.
- python.src.lib.iters.groupwise(iterable: Iterable[T], size: int) Iterator[Tuple[T, ...]]
Iterate over something in buckets of a given size.
1from __future__ import generator_stop
2
3from collections import deque
4from itertools import count, islice, tee
5from typing import Any, Iterable, Iterator, Optional, Tuple, TypeVar
6
7from .factors import proper_divisors
8
9T = TypeVar("T")
10
11
12def abundants(stop: Optional[int] = None) -> Iterator[int]:
13 """Iterate over the abundant numbers."""
14 if stop is None:
15 iterator: Iterable[int] = count(12)
16 else:
17 iterator = range(12, stop)
18 for x in iterator:
19 if sum(proper_divisors(x)) > x:
20 yield x
21
22
23def consume(iterator: Iterable[Any], n: Optional[int] = None) -> None:
24 "Advance the iterator n-steps ahead. If n is None, consume entirely. (From itertools recipes)"
25 # Use functions that consume iterators at C speed.
26 if n is None:
27 deque(iterator, maxlen=0)
28 else:
29 next(islice(iterator, n, n), None)
30
31
32def digits(x: int, base: int = 10) -> Iterator[int]:
33 """Iterate over the digits of a number in a given base."""
34 while x:
35 x, y = divmod(x, base)
36 yield y
37
38
39def groupwise(iterable: Iterable[T], size: int) -> Iterator[Tuple[T, ...]]:
40 """Iterate over something in buckets of a given size."""
41 iters = tee(iterable, size)
42 for idx, x in enumerate(iters):
43 for _ in range(idx):
44 next(x, None)
45 return zip(*iters)
46
47
48def spiral_corners(i: int) -> Tuple[int, int, int, int]:
49 r = range((2 * i - 1)**2 + 1, (2 * i + 1)**2 + 1)
50 return (
51 r[1 * 2 * i - 1],
52 r[2 * 2 * i - 1],
53 r[3 * 2 * i - 1],
54 r[4 * 2 * i - 1]
55 )