A little Python!

The programming language one, not the snake one!

Hello pals!
Some time ago, I came across a problem in which I had to flatten an array of objects. That is, the elements of the array can be primitives or arrays. The end results is to be an array of primitives.

I used python to implement this since it allows much more compact snippets for such jobs.

Here is the code 🙂

def flatten(lst):
 return sum( ([x] if not isinstance(x, list) else flatten(x)
 for x in lst), [] )
 
lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
print flatten(lst)

Alright! Let’s inspect the code. Here we have a method called “flatten”, which takes only one element “lst” (as for list). When I said we can write compact snippets, I meant this.
The function consists of only a return statement, though the function is a recursive one 😉
Let’s follow through return statement!
it returns the result of “sum” function. As you may know, “sum” in python also concatenates lists (arrays).
Moreover, inside the sum, we have a for loop that also includes an if-else block. We can also rewrite is as:

for x in lst:
 if not isinstance(x, list):
  [x]
 else:
  flatten(x)

In this form, this should be quite understandable. Despite that, I’ll comment on it. It is taking the primitive element and making it into a one-element array. Then, it merges these one-element arrays into one array.
Here, for the lists inside our array, we need to call the function again because we may have multiple-depth lists inside our array.

There are two ways to make a set of primitives into array, first we can use sum function like above,
the other is putting it inside square brackets.
The reason we are using sum is, we specify start for the sum function. Here it is specified as empty list. If we use square brackets, foreach iteration in the recursion, we would have put it inside another list and at the end, we would have a multi-dimensional array with one element.

Last two lines is to test the function for a variety of cases. As you can see, we have empty lists, empty multi-dimensional lists, primitives, lists containing lists, and regular primitive lists.
At the end, you can see the runtime result as successful flattening.
(Here is a link to an online compiler in case you don’t have one.)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s