1

Is there a function that returns the (length of the) longest string that all values start with in a list:

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

Should return: "flex" or 4

And for this: ["flexible","flexile","flexion","flexor","ape"], it should return an empty string or 0;

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Janghou
  • 1,613
  • 1
  • 21
  • 30

2 Answers2

15
>>> import os
>>> os.path.commonprefix(["flexible","flexile","flexion","flexor"])
'flex'
Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

This should work for any iterables:

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
ryachza
  • 4,460
  • 18
  • 28