How do I write an arrow function in ES6 recursively?

Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion. The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like … Read more

Creating a nested dictionary from a flattened dictionary

Here is my take: def nest_dict(flat): result = {} for k, v in flat.items(): _nest_dict_rec(k, v, result) return result def _nest_dict_rec(k, v, out): k, *rest = k.split(‘_’, 1) if rest: _nest_dict_rec(rest[0], v, out.setdefault(k, {})) else: out[k] = v flat = {‘X_a_one’: 10, ‘X_a_two’: 20, ‘X_b_one’: 10, ‘X_b_two’: 20, ‘Y_a_one’: 10, ‘Y_a_two’: 20, ‘Y_b_one’: 10, ‘Y_b_two’: … Read more

find all subsets that sum to a particular value

def total_subsets_matching_sum(numbers, sum): array = [1] + [0] * (sum) for current_number in numbers: for num in xrange(sum – current_number, -1, -1): if array[num]: array[num + current_number] += array[num] return array[sum] assert(total_subsets_matching_sum(range(1, 10), 9) == 8) assert(total_subsets_matching_sum({1, 3, 2, 5, 4, 9}, 9) == 4) Explanation This is one of the classic problems. The idea … Read more

How does the C++ compiler evaluate recursive constexpr functions so quickly?

constexpr functions have no side-effects and can thus be memoized without worry. Given the disparity in runtime the simplest explanation is that the compiler memoizes constexpr functions during compile-time. This means that fibonacci(n) is only computed once for each n, and all other recursive calls get returned from a lookup table.