Return leading string common to (the start of) words in a list in python -
i'm having 1 of experiences write should trivial , takes more lines of code expected. can suggest more elegant solution problem of pulling (from list of words) leading string mutual them all? i'm included code can laugh @ it.
def _allstartwith( words ): """ homecoming leading string mutual (the start of) words in list """ n = len( words[0] ) other in words[1:]: if other != words[0]: n = min( n, _samefor( other, words[0] ) ) homecoming words[0][:n] where
def _samefor( word1, word2 ): """ how many letters same before 1 false ?""" homecoming ( [ c1==c2 c1, c2 in zip( word1, word2 ) ] + [ false ] ).index( false ) for example,
_allstartwith( [ 'foo2you , you','foo bar , you'] ) 'foo'
you abuse os.path.commonprefix():
>>> import os >>> os.path.commonprefix(['foo2you , you', 'foo bar , you']) 'foo' here's its code:
# homecoming longest prefix of list elements. def commonprefix(m): "given list of pathnames, returns longest mutual leading component" if not m: homecoming '' s1 = min(m) s2 = max(m) i, c in enumerate(s1): if c != s2[i]: homecoming s1[:i] homecoming s1 python
No comments:
Post a Comment