Bob T
Bob T

Reputation: 318

Test if all instances of character in string are consecutive in Python

I'm looking for help creating a function to test whether all instances of a character in a string are "consecutive". I use quotes because I want to treat the case where the instances are all at the beginning and end of the string as "consecutive" (they "wrap", i.e., "111000000111")

Example cases, testing for instances of number 1's being consecutive:

result1 = testConsecutive('1110000011') ## GOOD (number 1's "wrap")
result2 = testConsecutive('1000000111') ## GOOD (number 1's "wrap")
result3 = testConsecutive('0000111000') ## GOOD (1's consecutive)
result4 = testConsecutive('0000000010') ## GOOD (1's consecutive)
result5 = testConsecutive('0000010100') ## FAIL (1's non-consecutive)
result6 = testConsecutive('1010001010') ## FAIL (1's non-consecutive)
result7 = testConsecutive('1100010011') ## FAIL (1's non-consecutive)
result8 = testConsecutive('1100011000') ## FAIL (1's non-consecutive)

The following code works for all cases above except result8:

def testConsecutive(string):
    solution = string.lstrip('1').strip('0').count('0')

    if solution == 0:
       return True
    else:
       return False

Thanks!

Upvotes: 2

Views: 77

Answers (3)

ilyas patanam
ilyas patanam

Reputation: 5324

If you want to use a strip based solution you will have to test two cases either 1's are padding your string of zeroes or 0's are padding your string of ones:

def testConsecutive(string):
    solution1 = string.strip('0').count('0')
    solution2 = string.strip('1').count('1')

    if solution1 == 0 or solution2 == 0:
       return True
    else:
       return False

Upvotes: 2

shx2
shx2

Reputation: 64318

I don't see how you can achieve that using a strip-based solution.

Here is an alternative approach.

Assuming your string only contains "0"s and "1"s, you can use itertools.groupby to group consecutive occurences. If you get 3 groups or fewer, the strings satisfy the predicate.

import itertools
def testConsecutive(s):
    groups = itertools.groupby(s)
    return len(list(groups)) <= 3

Upvotes: 4

Serge
Serge

Reputation: 121

def testConsecutive(string):
    return not '1' in string.lstrip('1').rstrip('1') or not '0' in string.lstrip('0').rstrip('0')

Quick and dirty solution, regexes surely do it better

Upvotes: 3

Related Questions