diff --git a/src/underscore.py b/src/underscore.py index 63f7ca7..1819554 100644 --- a/src/underscore.py +++ b/src/underscore.py @@ -362,6 +362,54 @@ def min(self): return self._wrap(list()) return self._wrap(min(self.obj)) + def list_min_index_value(self): + """ + Given a list, returns the index which has the minimum value, along with the value. + It assumes the values are comparable objects eg integers, strings, objects that implement __cmp__ + :param values_list: A list to be searched upon + :return: A list of index(es) that have the minimum value + """ + + if len(self.obj) == 0: + return self._wrap([]) + + min_value = min(self.obj) + how_many = self.obj.count(min_value) + c = -1 + index_list = [] + for idx, value in enumerate(self.obj): + if value == min_value: + index_list.append(idx) + + if len(index_list) > how_many: + break + + return self._wrap(index_list) + + def list_max_index_value(self): + """ + Given a list, returns the index which has the maximum value, along with the value. + It assumes the values are comparable objects eg integers, strings, objects that implement __cmp__ + :param values_list: A list to be searched upon + :return: A list of index(es) that have the maximum value + """ + + if len(self.obj) == 0: + return self._wrap([]) + + max_value = max(self.obj) + how_many = self.obj.count(max_value) + index_list = [] + for idx, value in enumerate(self.obj): + if value == max_value: + index_list.append(idx) + + if len(index_list) >= how_many: + break + + + return self._wrap(index_list) + def shuffle(self): """ Shuffle an array. """ diff --git a/tests/test_arrays.py b/tests/test_arrays.py index 82962b2..8c076b6 100644 --- a/tests/test_arrays.py +++ b/tests/test_arrays.py @@ -179,6 +179,37 @@ def test_range(self): [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final' ' example in the Python docs') + def test_min_list(self): + res = _([-55, -55, -7, 15, 2, 1, -7, 4]).list_min_index_value() + expected = [0, 1] + assert res == expected + + def test_min_empty_list(self): + res = _([]).list_min_index_value() + expected = [] + assert res == expected + + def test_min_one_value(self): + res = _([2, 2, 2, 2]).list_min_index_value() + expected = [0, 1, 2, 3] + assert res == expected + + def test_max_list(self): + res = _([-55, -55, -7, 15, 2, 1, -7, 4]).list_max_index_value() + expected = [3] + assert res == expected + + def test_max_empty_list(self): + res = _([]).list_max_index_value() + expected = [] + assert res == expected + + def test_max_one_value(self): + res = _([2, 2, 2, 2]).list_max_index_value() + expected = [0, 1, 2, 3] + assert res == expected + + if __name__ == "__main__": print("run these tests by executing `python -m unittest" " discover` in unittests folder")