Created
October 17, 2010 15:24
-
-
Save stucchio/630939 to your computer and use it in GitHub Desktop.
Inverse Image pattern (remarkably useful)
This file contains 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 inv_image(f, collection): | |
"""Returns the inverse image (in the mathematical sense) | |
of the function applied to the collection. | |
""" | |
result = {} | |
for x in collection: | |
img = f(x) | |
if result.has_key(img): | |
result[img].add(x) | |
else: | |
result[img] = set([x,]) | |
return result | |
assert(inv_image(lambda x: x % 3, range(15)) == { | |
0: set([0, 9, 3, 12, 6]), | |
1: set([1, 10, 4, 13, 7]), | |
2: set([8, 2, 11, 5, 14]) | |
} ) | |
students_with_grade = [("Joe", 'F'), ("Bill", "B"), ("Eve", "B"), ("Josh", "A") ] | |
assert( inv_image(lambda x: x[1], students_with_grade) == | |
{'A': set([('Josh', 'A')]), | |
'B': set([('Bill', 'B'), ('Eve', 'B')]), | |
'F': set([('Joe', 'F')]) | |
} ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment