3 points · by RiderOfGiraffes · 17y ago · 8 comments
Write a routine that returns True iff all the elements of the input list are equal.
Here's a non-pythonic routine:
def is_constant(l):
for i in range(1,len(l)):
if l[0]!=l[i]:
return False
return True
That's a simple, early-terminating imperative loop. Here's a slower and not necessarily clearer version: def is_constant(l):
return min(l)==max(l)
Personally, the fact that the code is short really appeals to me, but some people would find it unclear in how (and why!) it works.Here's an even less clear version:
def is_constant(l):
return len(l)*[True]==[ l[0]==a for a in l ]
I'd specifically like to know the answer to this question: Suppose you have to maintain a piece of code that performs this function. What would your ideal code be to find?Extra marks available for code that deals cleanly with corner cases: empty lists, tuples and generators.
def is_constant(l):
return reduce(lambda x, y: x and (y == l[0]), l, True) def f(x): return not x or list(x) == [x[0]] * len(x)
Does have the downside that it constructs a list, which the min==max solution doesn't.I wonder if there is a single "ideal" solution ...
def f(x): 0 == sum([y - x[0] for y in x])