m-len(t)) for i in range(n,m): if s[i:] == t[:m-i]: return m-i return 0 overlap('12345' , '3456') overlap('1234' , '12345') overlap('1234' , '2345') from ortoolpy import tsp def shortest_superstring(words): """࠷จࣈྻ""" words = [''] + words n = len(words) dist = {(i, j): len(t) - overlap(s, t) for i, s in enumerate(words) for j, t in enumerate(words) if i != j} _, lst = tsp(words, dist) return ''.join(words[j][len(words[j]) - dist[i, j]:] for i, j in zip(lst, lst[1:])) shortest_superstring(['TAG', 'ACTA', 'GTC', 'GAC'])