os.path.commonprefix inadequacies
Alex Martelli
aleaxit at yahoo.com
Wed Aug 1 08:33:46 EDT 2001
"Dean & Yang Draayer" <draayer at surfglobal.net> wrote in message
news:mailman.996614459.6734.python-list at python.org...
...
> def commonprefix(L, empty=''):
> if not L:
> return empty
> m = min(map(len, L))
> if m == 0:
> return empty
> L0 = L[0]
> for i in xrange(1, len(L)):
> for j in xrange(m):
> if L[i][j] != L0[j]:
> m = j
> if m == 0:
> return empty
> break
> return L0[:m]
What about a simpler, more concise expression:
def commonprefix(seq, default_empty=''):
try:
leng = 0
for tuple in zip(*seq):
if tuple[1:] != tuple[:-1]: break
leng += 1
return seq[0][:leng]
except TypeError: return default_empty
Probably not as fast as yours, but simpler, as
it exploits zip's behavior (truncation at
shortest argument sequence, raising TypeError
if the sequence of sequences is empty). It
only needs default_empty when called with an
empty sequence of sequences, otherwise uses
the initial slice (perhaps an empty one) from
the first sequence as the null result, which
should automatically ensure the right type
(more or less:-).
Alex
More information about the Python-list
mailing list