首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试字符串是否包含相同符号的交替数,并且是加2的奇数?

如何测试字符串是否包含相同符号的交替数,并且是加2的奇数?
EN

Stack Overflow用户
提问于 2015-04-03 06:50:22
回答 1查看 194关注 0票数 0

如何测试字符串是否包含相同符号的交替数,并且是加2的奇数?

代码语言:javascript
复制
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")
EN

回答 1

Stack Overflow用户

发布于 2015-04-03 07:07:07

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29423783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档