Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- from random import randrange
- from statistics import mean as st_mean, median as st_median, mode as st_mode
- from typing import Any, Callable, Iterable, Tuple, TypeVar
- ''' https://pastebin.com/xhfT1njJ '''
- class BranchedGenerator:
- _n: Iterable[int]
- _stop_value: Any
- def __init__(self, n: Iterable[int], stop: Any):
- self._n = n
- self._stop_value = stop
- @property
- def new(self):
- return
- def wrapper1(f):
- new = (yield)
- # SyntaxError: 'yield' inside generator expression
- yield f((y for _ in new if (y := (yield)) or True))
- return
- _T1 = TypeVar('_T1')
- _T2 = TypeVar('_T2')
- def wrapper2(ns: Iterable[_T1], fs: Iterable[Callable[[Iterable[_T1]], _T2]]) -> Tuple[_T2, ...]:
- def has_new():
- while new:
- yield True
- while True:
- yield False
- new = True
- xwf = tuple(map(wrapper1, fs))
- for x in xwf:
- next(x)
- x.send(has_new)
- next(x)
- for n in ns:
- for x in xwf:
- x.send(n)
- new = False
- return tuple(map(next, xwf))
- def source(n: int) -> Iterable[int]:
- return (randrange(-9, 9000) for _ in range(n))
- normal = (tuple, st_mean, st_median, st_mode)
- def test0():
- sample = tuple(source(25))
- s_tuple, s_mean, s_median, s_mode = wrapper2(sample, normal)
- b_tuple, b_mean, b_median, b_mode = (f(s_tuple) for f in normal)
- assert all((
- s_tuple == b_tuple,
- s_mean == b_mean,
- s_median == b_median,
- s_mode == b_mode
- ))
- def test1():
- sample = source(25)
- s_tuple, s_mean, s_median, s_mode = wrapper2(sample, normal)
- b_tuple, b_mean, b_median, b_mode = (f(s_tuple) for f in normal)
- print(
- 'Test1:'
- '\nTuple', s_tuple, '\n', b_tuple, '\n==?', v0 := s_tuple == b_tuple,
- '\nMean', s_mean, '\n', b_mean, '\n==?', v1 := s_mean == b_mean,
- '\nMedian', s_median, '\n', b_median, '\n==?', v2 := s_median == b_median,
- '\nMode', s_mode, '\n', b_mode, '\n==?', v3 := s_mode == b_mode,
- '\nPasses', ''.join('01'[v * 1] for v in (v0, v1, v2, v3)), 'All?', all((v0, v1, v2, v3))
- )
- if __name__ == '__main__':
- test0()
- test1()
Advertisement
Add Comment
Please, Sign In to add comment