Last active
April 7, 2017 17:36
-
-
Save rodrigodev/8794d49c4a2206e0a94b52d7a92a6cb8 to your computer and use it in GitHub Desktop.
A smart way to group a list of integers given a min distance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def smart_group_by_nearest(distance, int_list): | |
| int_list.sort() | |
| grouped_list = [[int_list[0]]] | |
| for x in int_list[1:]: | |
| if x - grouped_list[-1][0] <= distance: | |
| grouped_list[-1].append(x) | |
| else: | |
| grouped_list.append([x]) | |
| return grouped_list | |
| #remove small groups if wanted | |
| #return [x for x in grouped_list if len(x) > 1] | |
| if __name__ == "__main__": | |
| int_list = [5, 10, 12, 1, 10, 4] | |
| print smart_group_by_nearest(1, int_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment