0

How can I make a boolean expression when I need to check if one string is simply another string repeated multiple times.

For example:

is_periodiek('ABABABABABABABABABABABABABABABABABAB', 'AB')
>>> True

is_periodiek('ABABABABABABABABABABABABABABABABABAB', 'ABA')
>>> False

is_periodiek('ABABABABABABABABABABABABABABABABABAB', 'ABAB')
>>> True

I think I need to make a 'for' loop but it never found the solution.

kdopen
  • 8,032
  • 7
  • 44
  • 52
Victor
  • 65
  • 7
  • Doesn't this answer your question? http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python – adrin Nov 24 '14 at 21:16
  • did you mean the string appears Consecutive by *mutiple times* ? – Mazdak Nov 24 '14 at 21:18
  • yes that is what I mean. Sorry for my bad English. – Victor Nov 24 '14 at 21:19
  • are you counting overlapping? – Padraic Cunningham Nov 24 '14 at 21:20
  • No you need to take the second string and place it in the first string. If you can do it like 5 times and you used all the elements from the first string it returns True. But if you preserve elements from the first string and you can't continue because it's too short in comparison to the second string you need to return False. – Victor Nov 24 '14 at 21:25

3 Answers3

1
is_periodiek = lambda text, sub: not text.replace(sub, '')
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

As you wand the pattern appears Consecutive , you can split your string by pattern , if you get a list with empty strings , you can return True , else False :

>>> s='ABABABABABABABABABABABABABABABABABAB'
>>> s.split('AB')
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
>>> s.split('ABA')
['', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B']
>>> s.split('ABAB')
['', '', '', '', '', '', '', '', '', '']

so as says in comment you can get that boolean value with this compare :

>>> len(''.join(s.split('AB'))) == 0
True
>>> len(''.join(s.split('ABA'))) == 0
False
>>> len(''.join(s.split('ABAB'))) == 0
True

Also you can use it in a function :

def IsConsecutive(string,pattern):
    return len(''.join(string.split(pattern))) == 0
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Can be done with a recursive lambda:

is_periodiek = lambda x, y: x == y or (is_periodiek(x[len(y):], y) and x.find(y) == 0)
njzk2
  • 38,969
  • 7
  • 69
  • 107