Longest common prefix: Difference between revisions

Content added Content deleted
(→‎Python: Functional: revert to original version because the other version may have bad complexity; but use min & max instead of sort)
Line 58: Line 58:


===Python: Functional===
===Python: Functional===
To see if all the n'th characters are the same I compare the min and max characters in the lambda function.
We first observe that the longest common prefix of a set of strings must be the same as the longest common prefix of the lexicographically minimal and lexicographically maximal strings, since moving away lexicographically can only shorten the common prefix, never lengthen it. We <code>zip</code> the two strings, taking advantage of the fact that it stops at the end of the shortest sequence, to not need to worry about extra characters on the longer one. We compare each pair of characters and take them as long as they are equal.


<lang python>from itertools import takewhile
<lang python>from itertools import takewhile


def lcp(*s):
def lcp(*s):
return ''.join(a for a,b in takewhile(lambda (a,b): a == b,
return ''.join(ch[0] for ch in takewhile(lambda x: min(x) == max(x),
zip(min(s), max(s))))
zip(*s)))


assert lcp("interspecies","interstelar","interstate") == "inters"
assert lcp("interspecies","interstelar","interstate") == "inters"