python-more-itertools/0004-Add-prepend-recipe.patch
zhang-liang-pengkun 66430cef45 Add prepend recipe
Signed-off-by: zhang-liang-pengkun <zhangliangpengkun@xfusion.com>
2023-12-28 16:35:58 +08:00

81 lines
2.4 KiB
Diff

From a17e5e4f8d9d9b8e1932bda10a1ab5cf59290deb Mon Sep 17 00:00:00 2001
From: Bo Bayles <bbayles@gmail.com>
Date: Mon, 14 May 2018 21:20:08 -0500
Subject: [PATCH] Add prepend recipe
---
docs/api.rst | 1 +
more_itertools/recipes.py | 15 +++++++++++++++
more_itertools/tests/test_recipes.py | 16 ++++++++++++++++
3 files changed, 32 insertions(+)
diff --git a/docs/api.rst b/docs/api.rst
index 914e5bc..49459f3 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -110,6 +110,7 @@ These tools combine multiple iterables.
.. autofunction:: dotproduct
.. autofunction:: flatten
.. autofunction:: roundrobin
+.. autofunction:: prepend
Summarizing
diff --git a/more_itertools/recipes.py b/more_itertools/recipes.py
index ec5e756..3a7706c 100644
--- a/more_itertools/recipes.py
+++ b/more_itertools/recipes.py
@@ -33,6 +33,7 @@ __all__ = [
'pairwise',
'partition',
'powerset',
+ 'prepend',
'quantify',
'random_combination_with_replacement',
'random_combination',
@@ -548,3 +549,17 @@ def nth_combination(iterable, r, index):
result.append(pool[-1 - n])
return tuple(result)
+
+
+def prepend(value, iterator):
+ """Yield *value*, followed by the elements in *iterator*.
+
+ >>> value = '0'
+ >>> iterator = ['1', '2', '3']
+ >>> list(prepend(value, iterator))
+ ['0', '1', '2', '3']
+
+ To prepend multiple values, see :func:`itertools.chain`.
+
+ """
+ return chain([value], iterator)
diff --git a/more_itertools/tests/test_recipes.py b/more_itertools/tests/test_recipes.py
index f6d7680..81721fd 100644
--- a/more_itertools/tests/test_recipes.py
+++ b/more_itertools/tests/test_recipes.py
@@ -589,3 +589,19 @@ class NthCombinationTests(TestCase):
actual = mi.nth_combination(range(180), 4, 2000000)
expected = (2, 12, 35, 126)
self.assertEqual(actual, expected)
+
+
+class PrependTests(TestCase):
+ def test_basic(self):
+ value = 'a'
+ iterator = iter('bcdefg')
+ actual = list(mi.prepend(value, iterator))
+ expected = list('abcdefg')
+ self.assertEqual(actual, expected)
+
+ def test_multiple(self):
+ value = 'ab'
+ iterator = iter('cdefg')
+ actual = tuple(mi.prepend(value, iterator))
+ expected = ('ab',) + tuple('cdefg')
+ self.assertEqual(actual, expected)
--
2.39.0.windows.2