From Captain Obvious

Aug 27, 2017 15:53

On a (Python) interview a candidate is asked to consider a collection of values and answer if all of the values are the same. The answer was to populate a set with those values (one-liner in Python), then check its length. Why is it not a great idea and what should we do instead (maybe)?

python, algorithm

Leave a comment

Comments 4

yatur August 28 2017, 02:32:49 UTC
If there are many different values, creating a set would be a lot of work in which we are not really interested.
I would compare all items with the first one until either the difference is found, or the collection is exhausted. In C#:

// assuming collection is not empty
var first = c.First();
return !c.Any( x=> x != first);

Not sure what's the best way to do it in Python

Reply

aklepatc August 28 2017, 13:28:13 UTC
Exactly!

Also, in Python, set elements need to be hash-able which our values are not guaranteed to be. In general, mutable things are not hash-able in Python so the interviewer's answer simply won't work for list, dict, etc. values.

it = iter(collection)
first = next(it, None)
result = all(x == first for x in it)

Reply

aklepatc September 8 2017, 15:02:29 UTC
There is a subtle difference between "your" C# and "my" Python here.

I grab the first element then compare it with the "rest" of the collection. You grab the first element and compare it with the entire collection. Hence having to say "not not" in C#. On the other hand, this C# is a two-liner and Python is a 3-liner. Not a big deal, obviously, just my code micro-structure OCD talking ;)

Reply


aklepatc October 29 2017, 19:56:48 UTC
For the sake of completeness... Apparently, "adult" solution for the problem in Python looks something like this:

from itertools import groupby
g = groupby(collection)
result = next(g, True) and not next(g, False)

Reply


Leave a comment

Up