Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Pythonic way to find the longest common prefix of a list of lists?

Tags:

Given: a list of lists, such as [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]

Todo: Find the longest common prefix of all sublists.

Exists: In another thread "Common elements between two lists not using sets in Python", it is suggested to use "Counter", which is available above python 2.7. However our current project was written in python 2.6, so "Counter" is not used.

I currently code it like this:

l = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]
newl = l[0]
if len(l)>1:
    for li in l[1:]:
    newl = [x for x in newl if x in li]

But I find it not very pythonic, is there a better way of coding?

Thanks!

New edit: Sorry to mention: in my case, the shared elements of the lists in 'l' have the same order and alway start from the 0th item. So you wont have cases like [[1,2,5,6],[2,1,7]]

like image 717
lukmac Avatar asked Jun 29 '12 13:06

lukmac


People also ask

How do you find the largest common prefix?

Given the array of strings S[], you need to find the longest string S which is the prefix of ALL the strings in the array. Longest common prefix (LCP) for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2. For Example: longest common prefix of “abcdefgh” and “abcefgh” is “ABC”.

How do you find the common prefix in two strings in python?

path. commonprefix does exactly this: Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string ( '' ).


1 Answers

os.path.commonprefix() works well for lists :)

>>> x = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]
>>> import os
>>> os.path.commonprefix(x)
[3, 2, 1]
like image 126
user3246749 Avatar answered Sep 19 '22 01:09

user3246749