I’m working an example to help me learn how to use first-class functions in Python. In general, I’m satisfied with the solution I came up with, except for one line of code that screams “un-Pythonic” to me.
So the problem I’m working with is defined here. The puzzle seeks the single permutation (out of 720 possible) of six simple functions involving “2” that ultimately returns -3.
Here’s my solution, which simply dumps every possible six-function permutation and its result.
def perform (fun, arg):
return fun(arg)
def a(n):
return n + 2
def d(n):
return n / 2.
def m(n):
return n * 2
def p(n):
return n ** 2
def r(n):
return n ** 0.5
def s(n):
return n - 2
if __name__ == "__main__":
from itertools import permutations
for i, perm in enumerate(permutations([a, d, m, p, r, s])):
try:
k = perform(perm[5], perform(perm[4], perform(perm[3], perform(perm[2], perform(perm[1], perform(perm[0], 0))))))
except ValueError:
k = float('nan')
print "%03d. %s: %8.8f" % (i + 1, ''.join([x.__name__ for x in perm]), k)
The line that doesn’t seem right to me is the one with nested perform calls: k = perform(...perform(...(. What I need to do is apply the first function in the permutation tuple to 0, and then that function’s result to the second function in the tuple, and so on through the permutation tuple until I come up with the ultimate result of applying the component functions.
Is there a cleaner way to successively apply the functions in perm to the corresponding results, starting with 0 as an argument? I’ve toyed with map and recursion, but I haven’t been able to hit upon a solution any more elegant than the one above.
Why not simply:
or in a bit fancier way: