Skip to content

Commit

Permalink
Merge pull request aimacode#104 from Chipe1/util
Browse files Browse the repository at this point in the history
Changes in util.py
  • Loading branch information
norvig committed Mar 9, 2016
2 parents a198cd6 + d616b9d commit a606f70
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
14 changes: 7 additions & 7 deletions aimaPy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,12 @@ def some(predicate, seq):

return predicate(elem) or False

# TODO: rename to is_in or possibily add 'identity' to function name to
# TODO[COMPLETED]: rename to is_in or possibily add 'identity' to function name to
# clarify intent


def isin(elt, seq):
"""Like (elt in seq), but compares with is, not ==."""
def is_in(elt, seq):
"""Similar to (elt in seq), but compares with 'is', not '=='."""
return any(x is elt for x in seq)

#______________________________________________________________________________
Expand All @@ -125,15 +125,15 @@ def argmin(seq, fn):

def argmin_list(seq, fn):
"""Return a list of elements of seq[i] with the lowest fn(seq[i]) scores.’"""
smallest_score = len(min(seq, key=fn))
smallest_score = fn(min(seq, key=fn))

return [elem for elem in seq if fn(elem) == smallest_score]


def argmin_gen(seq, fn):
"""Return a generator of elements of seq[i] with the lowest fn(seq[i]) scores."""

smallest_score = len(min(seq, key=fn))
smallest_score = fn(min(seq, key=fn))

yield from (elem for elem in seq if fn(elem) == smallest_score)

Expand All @@ -152,14 +152,14 @@ def argmax(seq, fn):
def argmax_list(seq, fn):
"""Return a list of elements of seq[i] with the highest fn(seq[i]) scores.
Not good to use 'argmin_list(seq, lambda x: -fn(x))' as method breaks if fn is len"""
largest_score = len(max(seq, key=fn))
largest_score = fn(max(seq, key=fn))

return [elem for elem in seq if fn(elem) == largest_score]


def argmax_gen(seq, fn):
"""Return a generator of elements of seq[i] with the highest fn(seq[i]) scores."""
largest_score = len(min(seq, key=fn))
largest_score = fn(min(seq, key=fn))

yield from (elem for elem in seq if fn(elem) == largest_score)

Expand Down
6 changes: 3 additions & 3 deletions tests/utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ def test_some():
assert some(callable, [2, 3]) == 0


def test_isin():
def test_is_in():
e = []
assert isin(e, [1, e, 3]) == True
assert isin(e, [1, [], 3]) == False
assert is_in(e, [1, e, 3]) == True
assert is_in(e, [1, [], 3]) == False


def test_argmin():
Expand Down

0 comments on commit a606f70

Please sign in to comment.