From 49d68cefa5aa1ea617a2d6be5ee1444b4efb20cb Mon Sep 17 00:00:00 2001 From: foefl Date: Mon, 23 Mar 2026 11:21:53 +0100 Subject: [PATCH] add symmetric iteration routine, related to #5 --- src/dopt_basics/iteration.py | 19 +++++++++++++++++++ tests/test_iteration.py | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/dopt_basics/iteration.py create mode 100644 tests/test_iteration.py diff --git a/src/dopt_basics/iteration.py b/src/dopt_basics/iteration.py new file mode 100644 index 0000000..185c4d3 --- /dev/null +++ b/src/dopt_basics/iteration.py @@ -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() diff --git a/tests/test_iteration.py b/tests/test_iteration.py new file mode 100644 index 0000000..7ace088 --- /dev/null +++ b/tests/test_iteration.py @@ -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