Longest common prefix: Difference between revisions

→‎Python: Functional: Added a definition of lcp in terms of a generic `transpose`
(→‎{{header|JavaScript}}: Added an ES6 draft)
(→‎Python: Functional: Added a definition of lcp in terms of a generic `transpose`)
Line 1,730:
return ''.join(a for a,b in takewhile(lambda x: x[0] == x[1],
zip(min(s), max(s))))</lang>
 
 
Or, defined in terms of a generic '''transpose''' function:
<lang Python>from itertools import (takewhile)
 
 
# lcp :: [String] -> String
def lcp(xs):
return ''.join(
x[0] for x in takewhile(allSame, transpose(xs))
)
 
 
# TEST --------------------------------------------------
 
# main :: IO ()
def main():
def showPrefix(xs):
return ''.join(['[' + ', '.join(xs), '] -> ', lcp(xs)])
 
print (*list(map(showPrefix, [
["interspecies", "interstellar", "interstate"],
["throne", "throne"],
["throne", "dungeon"],
["cheese"],
[""],
["prefix", "suffix"],
["foo", "foobar"]])), sep='\n'
)
 
 
# GENERIC FUNCTIONS -------------------------------------
 
 
# allSame :: [a] -> Bool
def allSame(xs):
if 0 == len(xs):
return True
else:
x = xs[0]
return all(map(lambda y: x == y, xs))
 
 
# transpose :: [[a]] -> [[a]]
def transpose(xs):
return map(list, zip(*xs))
 
 
# TEST ---
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>[interspecies, interstellar, interstate] -> inters
[throne, throne] -> throne
[throne, dungeon] ->
[cheese] -> cheese
[] ->
[prefix, suffix] ->
[foo, foobar] -> foo</pre>
 
=={{header|Racket}}==
9,659

edits