Skip to content

Instantly share code, notes, and snippets.

@colematt
Last active September 2, 2020 21:13
Show Gist options
  • Save colematt/14401b7970605ace554661eeb5daeaf5 to your computer and use it in GitHub Desktop.
Save colematt/14401b7970605ace554661eeb5daeaf5 to your computer and use it in GitHub Desktop.
[Partition a set into a ordered set of disjoint subsets] #python
#!/usr/bin/python3
"""
File: partition.py
Author: Matthew Cole
Date: 6/7/16
"""
def partition(collection, partitions):
"""
Partition a collection into a list of len(partitions)+1 disjoint unsorted lists of elements,
whose union is collection,defined as: [-inf,part0),...[part_m,part_m+1),...,[part_n-1,inf].
Partitions itself must be an iterable, and collection must be orderable.
"""
from operator import ge, lt
partitions = sorted(set(partitions))
#Set up the buckets
filters = [list(filter(lambda x: lt(x,partitions[0]),collection))]
filters.extend([list(filter(lambda x: ge(x,partitions[i]) and lt(x,partitions[i+1]),collection)) for i in range(len(partitions)-1)])
filters.append(list(filter(lambda x: ge(x,partitions[-1]),collection)))
return(filters)
if __name__ == "__main__":
print(partition([1,9,4,16,16.7,10,1,100,200,-40], [10,1,10,100]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment