Last active
September 13, 2017 21:18
-
-
Save stiteler/f2dbf315c75d198aa5e9ab2fa1c51bc8 to your computer and use it in GitHub Desktop.
Longest common substring for many strings with @dokipen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import izip | |
def longest_common_substring(string_list): | |
def _iter(): | |
for row in izip(*string_list): | |
s = set(row) | |
if len(s) == 1: | |
yield s.pop() | |
else: | |
return | |
return ''.join(_iter()) | |
if __name__ == '__main__': | |
test = [ | |
'abcdef', | |
'abcdefg', | |
'abcdefgh', | |
'abcdefghi' | |
'abcdefghij', | |
] | |
print longest_common_substring(test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original idea and code came from Eric here: http://stackoverflow.com/questions/18715688/find-common-substring-between-two-strings and @dokipen & I adapted it to accept many strings and to use izip