Skip to content

Instantly share code, notes, and snippets.

@Zheaoli
Created September 22, 2017 03:45
Show Gist options
  • Save Zheaoli/3266319fb8e88a192bde240b9cfdd527 to your computer and use it in GitHub Desktop.
Save Zheaoli/3266319fb8e88a192bde240b9cfdd527 to your computer and use it in GitHub Desktop.
def groupBy(func):
def inner(data):
assert isinstance(data,list)
temp_dict={}
for value in data:
if func(value) not in temp_dict:
temp_dict[func(value)]=[value]
else:
temp_dict[func(value)].append(value)
return temp_dict
return inner
def test_group_by():
data=groupBy(lambda x: x%2)([1,2,3])
assert data == {1:[1,3], 0:[2]}
data=groupBy(lambda x: x%2)([])
assert data == {}
data=groupBy(lambda x: x%2)(None)
# raise assert error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment