How to reduce lines of code [python]

Vaibhav Raj Saxena
3 min readJan 23, 2022

One of the best ways of solving a problem, be it a coding or any other problem, is to break it down to smaller chunks. Once you have small chunks of problem to act upon, its easy to find a solution and even easier to make it efficient. Once you have solution to each of the small chunks of problem, the last part is to combine the solutions.

Lets look at an example. There is a list of words and we need to find a list of all possible concatenated words using all the words in the list.

So if I have a list of words, the output should be something like this with each string formed by using the words from the initial list:

Now, if we start by using “for-loop” in above problem, it would start getting complicated as the list of words start increasing. Also there can be scenarios where multiple strings are same in the list of words, which than need to be negated.

Python comes with a powerful module “itertools”. This module has inbuilt functions which can iterate on input items and perform looping in an efficient manner. One such function is permutations. This function, as the name suggests, uses the input list and arranges them in all possible ways. The function takes another parameter which decides on the number of elements to be considered for creating permutation. If this parameter is not provided, the function runs with all the elements considered.

So, by using permutations we can get something like this:

Now we have a solution. But above solution uses multiple variables for combining the permuted list and forming a new list, which internally requires copying the object into multiple variables, making it less efficient.

Another problem with above solution is if we have similar string multiple times, the end list have duplicate items. Something like this:

To improve this solution further, we can do two things:

  • Remove the for loop being used with a map function. Map function is again an iterator and can have first argument as a function that can be applied to all the items of a list, passed as the second argument.
  • Instead of converting the output of itertools.permutations in a list, we change it into a Set. This remove any duplicate values.

We have a single line solution that creates permutation from a list of words , removes duplicates and combines each list into a string.

--

--