Advertisement
here2share

# commonprefix.py

Feb 22nd, 2020
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. # commonprefix.py
  2.  
  3. from os.path import commonprefix
  4. v = commonprefix('outstanding outside outshines outspoken'.split())
  5. print v
  6.  
  7. # longestcommonprefix.py
  8.  
  9. zzz = '''
  10. hello
  11. world
  12. forecastable
  13. specialxyz
  14. xyz
  15. foresight
  16. shortabcdefghijklmnopqrstuvwxyz
  17. longestprefix
  18. shortest
  19. shortage
  20. longestxyz
  21. long
  22. foretold
  23. forever
  24. alpha
  25. foreign
  26. speciality
  27. beta
  28. longestabc
  29. short
  30. zebra
  31. forego
  32. abc
  33. shortxyz
  34. '''.splitlines()
  35.  
  36. def lcp(L):
  37.     longest = [0, []]
  38.     vL = 0
  39.     if len(L)>1:
  40.         sL = sorted(L)
  41.         v2 = ''
  42.         for i in range(len(L)-1):
  43.             v = commonprefix(sL[i:i+2])
  44.             if v:
  45.                 vL = len(v)
  46.                 v2 = v
  47.             else:
  48.                 if longest[0] == vL:
  49.                     if v2 not in longest[1]:
  50.                         longest[1].append(v2)
  51.                 elif longest[0] < vL:
  52.                     longest = [vL, [v2]]
  53.     return longest[-1]
  54. 0
  55. print lcp(zzz)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement