pewpew
pewpew

Reputation: 730

How to test if strings contain alternating numbers of same symbol that are odd numbers that increase by 2?

How to test if strings contain alternating numbers of same symbol that are odd numbers that increase by 2?

def test(fn,string):
    fn(string)

def alternating_colors(colors_string):
    print('The string "' + colors_string + '" is accepted') if colors_string.count('r') == ??? colors_string.count('b') == ??? else print('The string "' + colors_string + '" is not accepted')


# these tests should accept
test(alternating_colors, "r")
test(alternating_colors, "rbbb")
test(alternating_colors, "rbbbrrrrr")
test(alternating_colors, "b")
test(alternating_colors, "brrr")
test(alternating_colors, "brrrbbbbb")

# these tests should not accept
test(alternating_colors, "")
test(alternating_colors, "rr")
test(alternating_colors, "brrrr")
test(alternating_colors, "brrrrr")
test(alternating_colors, "rbbbrrr")
test(alternating_colors, "brbrbb")

Upvotes: 0

Views: 202

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114038

consecutives = list((len(list(x[1])) for x in itertools.groupby("rbbbrrrrr")))
# first get consecutive groupings
print all(y-x == 2 and x%2 and y%2 for x,y in zip(consecutives,consecutives[1:]))
#check that all values are odd and incrementing by 2

Upvotes: 1

Related Questions