Skip to content

Commit

Permalink
len_slice: Support sequences of integer indices.
Browse files Browse the repository at this point in the history
Adds support for sequences of integer indices. Normalizes their values
to ensure they are all valid first. Then simply counts how many integer
indices are present to get their length.
  • Loading branch information
jakirkham committed Dec 7, 2016
1 parent 12d1f63 commit bf893c3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
24 changes: 14 additions & 10 deletions kenjutsu/kenjutsu.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,18 +317,22 @@ def len_slice(a_slice, a_length=None):

new_slice = reformat_slice(a_slice, a_length)

if new_slice.stop is None:
if new_slice.step > 0:
raise UnknownSliceLengthException(
"Cannot determine slice length without a defined end point. " +
"The reformatted slice was " + repr(new_slice) + "."
)
else:
new_slice = slice(new_slice.start, -1, new_slice.step)
new_slice_size = 0
if isinstance(new_slice, slice):
if new_slice.stop is None:
if new_slice.step > 0:
raise UnknownSliceLengthException(
"Cannot determine slice length without a defined end"
" point. The reformatted slice was %s." % repr(new_slice)
)
else:
new_slice = slice(new_slice.start, -1, new_slice.step)

new_slice_diff = float(new_slice.stop - new_slice.start)
new_slice_diff = float(new_slice.stop - new_slice.start)

new_slice_size = int(math.ceil(new_slice_diff / new_slice.step))
new_slice_size = int(math.ceil(new_slice_diff / new_slice.step))
else:
new_slice_size = len(new_slice)

return(new_slice_size)

Expand Down
17 changes: 17 additions & 0 deletions tests/test_kenjutsu.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,23 @@ def test_len_slice(self):
len(each_range[a_slice])
)

a_slice = list()
a_slice.append(0 if start is None else start)
a_slice.append(0 if stop is None else stop)
a_slice.append(0 if step is None else step)

a_op = operator.itemgetter(*a_slice)

expected_result = None
try:
expected_result = a_op(each_range)
except IndexError:
pass

if expected_result is not None:
l = kenjutsu.len_slice(a_slice, size)
self.assertEqual(len(expected_result), l)

if start is not None:
a_slice = start

Expand Down

0 comments on commit bf893c3

Please sign in to comment.