如何测试字符串是否包含相同符号的交替数字,这些符号是奇数加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")
答案 0 :(得分: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