0

如何测试字符串是否包含相同符号的交替数字,这些数字是增加 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")
4

1 回答 1

1
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
于 2015-04-02T23:07:06.957 回答