Reputation: 399
I tried to solve the following problem:
my_function_composition(f,g)
input: two functions f and g, represented as dictionaries, such that g ◦ f exists.
output: dictionary that represents the function g ◦ f.
example: given f = {0:’a’, 1:’b’} and g = {’a’:’apple’, ’b’:’banana’}, return {0:’apple’, 1:’banana’}.
I have found a solution, but it feels pretty messy to me:
def my_function_composition(f,g): return {list(f.keys())[i]: list(g.values())[i] for i in f if list(f.values()) == list(g.keys())}
# example/test
w = {0:'a', 1:'b', 2: 'c'}
v = {'a': 'apple', 'b':'banana', 'c': 'carrot'}
my_function_composition(w,v)
According to the book, the next section includes loop problems, thus I assume there's an elegant one-line solution to this one.
Note: I would highly appreciate if you could provide comments to your solution, because I'm new with python
Upvotes: 0
Views: 182
Reputation: 106523
You can use dict comprehension:
d = {k: g[v] for k, v in f.items()}
d
becomes:
{0: 'apple', 1: 'banana'}
Upvotes: 2
Reputation: 43078
I would do it like this:
return {fk:g[fv] for fk, fv in f.items() if fv in g}
fk
is a key in f
and fv
is the value of the key in f
.
All I do is create a dictionary where the keys are made up of the keys of f
and the values are made up of looking up the values of f
in g
(if they exist).
Just to be pedantic, I added the if fv in g
, which I don't think is a requirement of this exercise.
Example:
>>> def fcomp(f, g): return {fk:g[fv] for fk, fv in f.items() if fv in g}
...
>>> fcomp({0:'a', 1:'b', 2: 'c'}, {'a': 'apple', 'b':'banana', 'c': 'carrot'})
{0: 'apple', 1: 'banana', 2: 'carrot'}
>>>
Upvotes: 1