from collections import Counter
def is_valid_binary_string(test_string):
c = Counter(test_string)
# Not valid if anything other than 1s and 0s
if set(c.keys()) - {"0", "1"}:
return False
# Valid only if even number of 1s and odd number of 0s
return c["1"] % 2 == 0 and c["0"] % 2 == 1
(?=^0*((10*){2})*?$)(?=^1*(01*)((01*){2})*?$)^.*$
(?= ) assert that
^ $ between the start and end of the string
0* (consume leading zeros)
( )*? there appears as many times as necessary
{2} two instances of
(10*) a 1 followed by any number of 0s
(?=^1* ((01*){2})*?$) perform the same check as before
(01*) but require an extra 0 at the start
使用来自
collections
的Counter
是另一种方法。它可以很容易地查找奇偶序列,并确保字符串只有1和0您不需要
regex
来完成此操作。使用string.count()
并检查响应是奇数还是偶数来实现这一点非常简单输出
如果你决定用正则表达式来做这件事,那么对于“simplify”的某些定义,这可能是合适的
这依赖于
{2}
量词要求所讨论的数字为2的倍数,而不是一次全部验证字符串,而是对字符串执行2次检查:第一次检查1的偶数,第二次检查0的偶数,再加上额外的0Demo
相关问题 更多 >
编程相关推荐