在查看了@pyfunc 发布的链接后,我想到了以下内容:
def shortest_of(lists):
return min(lists, key=len)
def contains_sublist(lst, sublst):
n = len(sublst)
return any((sublst == lst[i:i+n]) for i in xrange(len(lst)-n+1))
def longest_common(lists):
if not lists:
return ()
res = set()
base = shortest_of(lists)
length = len(base)
for i in xrange(length, 0, -1):
for j in xrange(length - i + 1):
candidate = ', ' + str(base[j:i+j]).strip('[]') + ','
#candidate = base[j:i+j]
for alist in lists:
if not candidate in ', ' + str(alist).strip('[]') + ',':
#if not contains_sublist(alist, candidate):
break
else:
res.add(tuple([int(a) for a in candidate[2:-1].split(',')]))
#res.add(tuple(candidate))
if res:
return tuple(res)
return ()
if __name__ == '__main__':
a = [1,0,2,5,4,3,1]
b = [1,2,5,4,3,0,1]
c = [1,3,5,4,2,0,1]
print longest_common([a,b,c])
print longest_common([b,c])
输出:
((5, 4),)
((0, 1), (5, 4))
编辑:
更新了使用字符串转换和匹配的解决方案,因为它恰好更快。以前的解决方案部分已被注释掉。此外,它现在提供了所有可能性。