diff options
Diffstat (limited to 'todo/util')
-rw-r--r-- | todo/util/__init__.py | 0 | ||||
-rw-r--r-- | todo/util/array.py | 5 | ||||
-rw-r--r-- | todo/util/range.py | 30 | ||||
-rw-r--r-- | todo/util/test_array.py | 12 | ||||
-rw-r--r-- | todo/util/test_range.py | 6 |
5 files changed, 53 insertions, 0 deletions
diff --git a/todo/util/__init__.py b/todo/util/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/todo/util/__init__.py diff --git a/todo/util/array.py b/todo/util/array.py new file mode 100644 index 0000000..bb4eee3 --- /dev/null +++ b/todo/util/array.py @@ -0,0 +1,5 @@ +def insert_position(x, xs, is_reversed: bool) -> int: + for i, y in enumerate(xs): + if is_reversed and x >= y or not is_reversed and x <= y: + return i + return len(xs) diff --git a/todo/util/range.py b/todo/util/range.py new file mode 100644 index 0000000..bd4b27e --- /dev/null +++ b/todo/util/range.py @@ -0,0 +1,30 @@ +from typing import NamedTuple, List + +class Range(NamedTuple): + start: int + length: int + +def from_indexes(indexes: List[int]) -> List[Range]: + ranges = [] + curr_range_start = 0 + curr_range_len = 0 + + last_index = -1 + + for index in sorted(indexes): + if index == curr_range_start + curr_range_len: + curr_range_len += 1 + else: + if curr_range_len > 0: + ranges.append(Range( + start = curr_range_start, + length = curr_range_len)) + curr_range_start = index + curr_range_len = 1 + + if curr_range_len > 0: + ranges.append(Range( + start = curr_range_start, + length = curr_range_len)) + + return ranges diff --git a/todo/util/test_array.py b/todo/util/test_array.py new file mode 100644 index 0000000..0186403 --- /dev/null +++ b/todo/util/test_array.py @@ -0,0 +1,12 @@ +from todo.util.array import insert_position + +def test_insert_position(): + assert insert_position(0, [], False) == 0 + assert insert_position(1, [1, 2, 3], False) == 0 + assert insert_position(2, [1, 2, 3], False) == 1 + assert insert_position(3, [1, 2, 3], False) == 2 + assert insert_position(8, [1, 2, 3], False) == 3 + assert insert_position(8, [3, 2, 1], True) == 0 + assert insert_position(3, [3, 2, 1], True) == 0 + assert insert_position(2, [3, 2, 1], True) == 1 + assert insert_position(1, [3, 2, 1], True) == 2 diff --git a/todo/util/test_range.py b/todo/util/test_range.py new file mode 100644 index 0000000..8a96636 --- /dev/null +++ b/todo/util/test_range.py @@ -0,0 +1,6 @@ +from todo.util.range import from_indexes, Range + +def test_from_indexes(): + assert from_indexes([]) == [] + assert from_indexes([1]) == [Range(1, 1)] + assert from_indexes([9, 6, 0, 10]) == [Range(0, 1), Range(6, 1), Range(9, 2)] |