Created
September 19, 2024 13:46
-
-
Save jdheywood/b0c1c5eacc6d574d3593e7f1094a93aa to your computer and use it in GitHub Desktop.
Chunky chunks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def chunks(iterable, chunk_size): | |
| """ | |
| Yield successive chunk_size chunks from iterable | |
| """ | |
| for i in range(0, len(iterable), chunk_size): | |
| yield iterable[i:i + chunk_size] | |
| class Chunky: | |
| """ | |
| Chunk up an iterable to list of lists, without the use of yield / generator. | |
| """ | |
| def __init__(self, iterable, chunk_size): | |
| self.iterable = iterable | |
| self.chunk_size = int(chunk_size) | |
| self.chunks = [] | |
| for i in range(0, len(self.iterable), self.chunk_size): | |
| self.chunks.append(list(self.iterable[i:i+self.chunk_size])) | |
| from unittest import TestCase | |
| class ChunkyTest(TestCase): | |
| def setUp(self): | |
| self.expected_result = [ | |
| [1, 2, 3], | |
| [4, 5, 6], | |
| [7, 8, 9], | |
| [10] | |
| ] | |
| def test_returns_expected_result_from_list(self): | |
| input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
| chunky = Chunky(input_list, 3) | |
| self.assertEqual(chunky.chunks, self.expected_result) | |
| def test_returns_expected_result_from_tuple(self): | |
| input_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) | |
| chunky = Chunky(input_tuple, 3) | |
| self.assertEqual(chunky.chunks, self.expected_result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment