Skip to content

Instantly share code, notes, and snippets.

@casperlehmann
Forked from skatenerd/declarative_inverses.py
Last active August 29, 2015 14:18
Show Gist options
  • Save casperlehmann/9d60bae4b0b92091957f to your computer and use it in GitHub Desktop.
Save casperlehmann/9d60bae4b0b92091957f to your computer and use it in GitHub Desktop.
#! -*- coding:utf8 -*-
def generate_inverse_transformations(left,right):
return (
lambda left: {
'uuid': left.get('key'),
'first_name': left.get('name').get('first'),
'last_name': left.get('name').get('last'),
'triple_tuples': [x for x in left.get('triples').items()],
'opposites': [{'first': x, 'second': y} for x,y in left.get('opposites')]
},
lambda right: {
'key': right.get('uuid'),
'name': {'first': right.get('first_name'), 'last': right.get('last_name')},
'triples': {x:y for x,y in right.get('triple_tuples')},
'opposites': [(x.get('first'),x.get('second')) for x in right.get('opposites')]
})
left_form = {
'key': 'abc123',
'name': {'first': 'joe', 'last': 'stein'},
'triples': {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
'opposites': [('low','high'),('big','small')]
}
right_form = {
'uuid': 'abc123',
'first_name': 'joe',
'last_name': 'stein',
'triple_tuples': [(1, 3), (2, 6), (3, 9), (4, 12), (5, 15)],
'opposites': [{'first': 'low', 'second': 'high'}, {'first': 'big', 'second': 'small'}]
}
#IMPLEMENT generate_inverse_transformations()
# So that, when:
#f, g = generate_inverse_transformations(left_form, right_form)
# THEN:
#f(left) == right
#g(right) == left
#f(g(right)) == right
# For any (left, right) of the same structure as left_form and right_form
#More specifically, if we have:
specific_input = {
'key': 'defghi',
'name': {'first': 'slug', 'last': 'ant'},
'triples': {1:2, 3:4},
'opposites': []
}
#Then, f(specific) should yield:
specific_output = {
'uuid': 'defghi',
'first_name': 'slug',
'last_name': 'ant',
'triple_tuples': [(1,2), (3,4)],
'opposites': []
}
f, g = generate_inverse_transformations(left_form, right_form)
print '''\
#f(left) == right: {}
#g(right) == left: {}
#f(g(right)) == right: {}
'''.format(
f(left_form) == right_form,
g(right_form) == left_form,
f(g(right_form)) == right_form
)
print '''\
#f(specific_input) == specific_output: {}
#g(specific_output) == specific_input: {}
#f(g(specific_output)) == specific_output: {}
'''.format(
f(specific_input) == specific_output,
g(specific_output) == specific_input,
f(g(specific_output)) == specific_output
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment