Joyride of Python One-liner Solution

Cassie Guo
2 min readJan 4, 2021

--

image source: pinterest

It is fascinating to see the use of one-liner python solutions for complex problems. Maybe it is time for us to take a moment to appreciate the Occam’s Razor Principle:

Non sunt multiplicanda entia sine necessitate (Entities are not to be multiplied without necessity).

image source: giphy

While it is nice to appreciate the simplicity of these solutions, bear in mind the caveat for practical software projects:

Now let’s start with a coding challenge…

Leetcode Problem 17 states:

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

This brilliant solution by huxley :

return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])

It might be daunting to look at it at the first sight, but let’s break it down by the functions it has:

  • lambda calculus
  • reduce()

Lambda calculus helps to slim down a normal function so that it can be fit into another higher order function. See this post to learn more about it. Here we use it to generate combinations of letters:

## solution by huxley at: https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8070/One-line-python-solutionkvmaps = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
myfunc = lambda acc, digit: [x+y for x in acc for y in kvmaps[digit]]
myfunc('k', 5)
>> ['kj', 'kk', 'kl']

Reduce function takes three argument: function to use , sequence of objects as iterable , and first object . reduce calls a sequence of function, and combines the results iteratively. In this case, we have

function_to_use = lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]]
sequence_objects = digits
first_object = ['']

To understand what happened inside reduce , here’s another way of coding it:

## acc stands for the accumulation of results## digits = '39'
acc = ['']
for d in digits:
acc = myfunc(acc,d)
print('digit: {}, acc: {}'.format(acc, d))
>> digit: ['d', 'e', 'f'], acc: 3
digit: ['dw', 'dx', 'dy', 'dz', 'ew', 'ex', 'ey', 'ez', 'fw', 'fx', 'fy', 'fz'], acc: 9

So instead of use a for-loop, reduce makes it possible in one line!

There are a lot to explore in one-liner solution…

Such as

Enjoy the ride!

Credits and reference:

Github page: https://github.com/finxter/PythonOneLiners

One-liner wiki page: https://wiki.python.org/moin/Powerful%20Python%20One-Liners

Stackoverflow on reduce:

https://stackoverflow.com/questions/45503434/how-lambda-works-with-reduce

--

--

Cassie Guo

Data Scientist; write about data culinary (data: ingredients 🍗🥬🧂🍅; model: recipe 📖; results: delicious dish🥘) and other shenanigans