add symmetric iteration routine, related to #5
This commit is contained in:
parent
24c06479b6
commit
49d68cefa5
19
src/dopt_basics/iteration.py
Normal file
19
src/dopt_basics/iteration.py
Normal file
@ -0,0 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from collections.abc import Iterator, Sequence
|
||||
from typing import TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def symmetric_iter(
|
||||
x: Sequence[T],
|
||||
) -> Iterator[T]:
|
||||
d = deque(x)
|
||||
|
||||
for idx in range(len(d)):
|
||||
if idx % 2 == 0:
|
||||
yield d.popleft()
|
||||
else:
|
||||
yield d.pop()
|
||||
25
tests/test_iteration.py
Normal file
25
tests/test_iteration.py
Normal file
@ -0,0 +1,25 @@
|
||||
from dopt_basics import iteration
|
||||
|
||||
|
||||
def test_symmetric_iter_1():
|
||||
l1_in = [1, 2, 3, 4, 5, 6]
|
||||
l1_out = [1, 6, 2, 5, 3, 4]
|
||||
|
||||
l1_calc = list(iteration.symmetric_iter(l1_in))
|
||||
assert len(l1_in) == len(l1_calc)
|
||||
assert len(l1_out) == len(l1_calc)
|
||||
|
||||
for truth, calc in zip(l1_out, l1_calc):
|
||||
assert truth == calc
|
||||
|
||||
|
||||
def test_symmetric_iter_2():
|
||||
l1_in = [1, 2, 3, 4, 5]
|
||||
l1_out = [1, 5, 2, 4, 3]
|
||||
|
||||
l1_calc = list(iteration.symmetric_iter(l1_in))
|
||||
assert len(l1_in) == len(l1_calc)
|
||||
assert len(l1_out) == len(l1_calc)
|
||||
|
||||
for truth, calc in zip(l1_out, l1_calc):
|
||||
assert truth == calc
|
||||
Loading…
x
Reference in New Issue
Block a user