I was working on project euler problem 14 and as a first attempt I whipped up this brute-force solution:
def collatz(n, memo={1: [1]}):
if n not in memo:
memo[n] = [n] + collatz(3 * n + 1 if n % 2 else n // 2)
return memo[n]
def p014():
return max(xrange(1, 10**6), key=lambda n: len(collatz(n)))
My question is about that lambda, I’m usually reluctant to use them but I don’t know any elegant way to avoid it in this case. Is there something in functools or other to chain two callables, or any other neat alternative I’m missing?
It would be lovely if there were a
composefunction — perhaps infunctools. There is not, nor do I expect there will be, alas. In the words of Raymond Hettinger,Here are two simple implementations of
composeas a callable class that you may find useful though:Also, see the
functionalpackage, which inspired this very simplecompose_manyfunction of mine a while ago: