Skip to content

Commit

Permalink
Add judge.utils.iterator.chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
quantum5 committed Mar 22, 2022
1 parent 15a1982 commit 1aaaea2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
7 changes: 7 additions & 0 deletions judge/utils/iterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from itertools import zip_longest


def chunk(iterable, size):
fill = object()
for group in zip_longest(*[iter(iterable)] * size, fillvalue=fill):
yield [item for item in group if item is not fill]
18 changes: 18 additions & 0 deletions judge/utils/tests/test_iterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import unittest
from itertools import chain

from judge.utils.iterator import chunk


class ChunkTestCase(unittest.TestCase):
def test_empty(self):
self.assertEqual(list(chunk([], 5)), [])

def test_normal(self):
for size in [10, 13, 100, 200]:
with self.subTest(f'chunk size {size}'):
result = list(chunk(range(100), size))
self.assertEqual(list(chain(*result)), list(range(100)))
for part in result[:-1]:
self.assertEqual(len(part), size)
self.assertLessEqual(len(result[-1]), size)

0 comments on commit 1aaaea2

Please sign in to comment.