获取列表中所有单词的最长公共字符串前缀

Get the longest common string prefix of all words in a list

是否有一个函数 return 是列表中所有值开头的最长字符串的(长度):

["flexible","flexile","flexion","flexor"]

应该return:"flex"或4

为此:["flexible","flexile","flexion","flexor","ape"],它应该 return 一个空字符串或 0;

>>> import os
>>> os.path.commonprefix(["flexible","flexile","flexion","flexor"])
'flex'

这应该适用于任何可迭代对象:

from itertools import takewhile

def commonprefix(xs):
  return map(lambda xs: xs[0],takewhile(lambda xs: len(set(xs)) == 1,zip(*xs)))

print len(commonprefix(["flexible","flexile","flexion","flexor"])) # 4
print len(commonprefix(["flexible","flexile","flexion","flexor","ape"])) # 0