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
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
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
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
from itertools import groupby
g = groupby(collection)
result = next(g, True) and not next(g, False)
Reply
Leave a comment