Week 4

Kenny Oh
2 min readDec 27, 2020

It’s Christmas this week so I’ll keep it pretty brief 🎄

I’m continuing with my interview preparation because I have a few assessments to complete and really want to focus on getting faster at coding challenges. Nearly all of the problems I’ve explored touch on processing arrays, and I find myself leaning on my past knowledge of javascript to tackle these problems. This is mostly because I prefer the syntax and I find the higher order functions easier to use given the more flexible acceptance of callback functions (more optional parameters such as currentIndex).

My favorite higher order function is .reduce() so I did some research on how to use this function in python. I came across this article that was really nice. reduce in python belongs to the functools library (which is another minor annoyance of mine — the fact that we have to import functools every time we want to reduce an array), though it’d be nice if it were globally accessible like map. One reason cited in the article was the inclusion of more pythonic and more performant functions like sum alland max.

reduce in python has the following signature functools.reduce(function, iterable[, initializer]). The iterable can take on the form of any “lists, tuples, range objects, generators, iterators, sets, dictionary keys and values, and any other Python objects that you can iterate over.”. The function argument is a callback function that takes exactly two arguments. The tricky part to wrapping your head around reducing is on the first iteration (in my opinion). This is where the initializer comes into play — if supplied, the first argument passed to function on the first iteration is the initializer. If left out, the first argument is the first item of the iterable.

I wanted to discuss the following solution provided in this commit, which uses reduce twice to achieve pretty different results. On line 117 it’s very succinct and written to achieve “straight-line code”. This is to be expected as I’m only finding the sum of all elements in an array. Compare that to lines 118 to 125 where more complex logic is needed to reduce an array into an object. When I came across this problem, it wasn’t immediately obvious to me that I should transform the array into an object, but whenever counting how many of something I should be quicker in recognizing a hash table is the best way of achieving this.

Anyways, getting comfortable with reduce in both python and javascript is critical in driving down my times on practice problems. Soon I’ll be able to process any array in no time at all 🤞🏼

--

--