Skip to content

Commit

Permalink
minor styling changes and more explicit test for generators
Browse files Browse the repository at this point in the history
  • Loading branch information
sbinq committed Jan 11, 2014
1 parent 3588987 commit 557cf11
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
3 changes: 1 addition & 2 deletions fn/iters.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,7 @@ def group_by(keyfunc, iterable):
"""
grouped = {}
for item in iterable:
key = keyfunc(item)
grouped.setdefault(key, []).append(item)
grouped.setdefault(keyfunc(item), []).append(item)
return grouped

def roundrobin(*iterables):
Expand Down
12 changes: 10 additions & 2 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,10 +491,18 @@ def test_grouper(self):
self.assertEqual(["G","x","x"], list(c))

def test_group_by(self):
iterable = (s for s in ['1', '12', 'a', '123', 'ab'])
grouped = iters.group_by(lambda s: len(s), iterable)
# verify grouping logic
grouped = iters.group_by(len, ['1', '12', 'a', '123', 'ab'])
self.assertEqual({1: ['1', 'a'], 2: ['12', 'ab'], 3: ['123']}, grouped)

# verify it works with any iterable - not only lists
def gen():
yield '1'
yield '12'

grouped = iters.group_by(len, gen())
self.assertEqual({1: ['1'], 2: ['12']}, grouped)

def test_roundrobin(self):
r = iters.roundrobin('ABC', 'D', 'EF')
self.assertEqual(["A","D","E","B","F","C"], list(r))
Expand Down

0 comments on commit 557cf11

Please sign in to comment.