Skip to content

Instantly share code, notes, and snippets.

@sixthgear
Created October 12, 2011 18:40
Show Gist options
  • Select an option

  • Save sixthgear/1282125 to your computer and use it in GitHub Desktop.

Select an option

Save sixthgear/1282125 to your computer and use it in GitHub Desktop.
import math
from collections import defaultdict
def hierarchize(flatlist, func):
output = defaultdict(list)
for item in flatlist:
output[func(item)].append(item)
return output.values()
def evens(n):
if n % 2 == 0:
return 1
else:
return 0
def primes(n):
if n < 2: return 1
if n == 2: return 0
if n % 2 == 0: return 1
for i in xrange(3, int(math.sqrt(n)+1), 2):
if n % i == 0: return 1
return 0
print hierarchize([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], evens)
print hierarchize([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], primes)
# OUTPUT:
# [[1, 3, 5, 7, 9, 11, 13, 15], [2, 4, 6, 8, 10, 12, 14]]
# [[2, 3, 5, 7, 11, 13], [1, 4, 6, 8, 9, 10, 12, 14, 15]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment