string - shortest repeated substring [PYTHON] -
is there quick method find shortest repeated substring , how many times occurs? if there non need return actual string ( last case ).
>>> repeated('ctctctctctctctctctctctct') ('ct', 12) >>> repeated('gatcgatcgatcgatc') ('gatc', 4) >>> repeated('gatcgatcgatcgatcg') ('gatcgatcgatcgatcg', 1)
because people think it's 'homework' can show efforts:
def repeated(sequentie): string = '' in sequentie: if not in string: string += items = sequentie.count(string) if items * len(string) == len(sequentie): return (string, items) else: return (sequentie, 1)
your method unfortunately won't work, since assumes repeating substring have unique characters. may not case:
abaabaabaabaabaaba
you on right track, though. shortest way can think of try , check on , on if prefix indeed makes entire string:
def find_shorted_substring(s): in range(1, len(s) + 1): substring = s[:i] repeats = len(s) // len(substring) if substring * repeats == s: return (substring, repeats)
it's not efficient, works. there better ways of doing it.
Comments
Post a Comment