Skip to content

Commit

Permalink
added another test and error handling for passing empty lists into ch…
Browse files Browse the repository at this point in the history
…oice functions.
  • Loading branch information
cmaclell committed Jan 22, 2019
1 parent 736e015 commit 0dca08d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
6 changes: 6 additions & 0 deletions concept_formation/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ def test_most_likely_choice():
with pytest.raises(ValueError):
utils.most_likely_choice([('a', -1)])

with pytest.raises(ValueError):
utils.most_likely_choice([])


def test_weighted_choice():
n = 1000
Expand All @@ -34,6 +37,9 @@ def test_weighted_choice():
with pytest.raises(ValueError):
utils.weighted_choice([('a', -1)])

with pytest.raises(ValueError):
utils.weighted_choice([])


def test_cv_mean():
for i in range(10):
Expand Down
5 changes: 5 additions & 0 deletions concept_formation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ def weighted_choice(choices):
if upto + w > r:
return c
upto += w
raise ValueError("Choices cannot be an empty list")


def most_likely_choice(choices):
Expand All @@ -167,8 +168,12 @@ def most_likely_choice(choices):
:return: the val with the hightest weight
:rtype: val
"""
if len(choices) == 0:
raise ValueError("Choices cannot be an empty list")

vals = [w for _, w in choices if w < 0]
if len(vals) > 0:
raise ValueError('All weights must be greater than or equal to 0')

updated_choices = [(prob, random(), val) for val, prob in choices]
return sorted(updated_choices, reverse=True)[0][2]

0 comments on commit 0dca08d

Please sign in to comment.