I came up with this when I tried to implement some autocompletion feature. The problem is to find a common substring (beginning from the start) for all strings in a given list.
I couldn't find an existing recipe that is doing this task, but I'm wondering if I just didn't look hard enough
Python, 15 lines
The code works as follows (commonletters):
Unfortunatelly, this is not enough (otherwise, this would be a cool one liner). If the strings in question had only identical letters at the beginning, we were done. But consider the strings ('hip','hop'). The result would be 'hp', which is clearly not the common start of both strings.
But, if we start over with the resultstring added to the stringlist as long as the resultstring changes, we'll get the one and only true result (a proof of that is left to the reader :-)
PLEASE note that the above statement was wrong with the old codeversion: <pre> def findcommonstart(strlist): strlist = strlist[:] common = getcommonletters(strlist) strlist.append(common) return getcommonletters(strlist) </pre>
The lambda function inside the reduce function does the same as the following regular function (and is, of course, more readable):
<pre> def myeq(op1,op2): if op1 == op2: return op1 </pre>
Please note that the algorithm does work equally well for all iterable types, not only strings (but remove the 'join' first)