Python中计算二进制字符串中全部为1的子字符串数量的程序
在Python中,我们有时需要计算二进制字符串中全部为1的子字符串数量。这个问题可以通过遍历字符串并统计全1子串的数量来解决。
下面是一个简单的程序来计算一个二进制字符串中全部为1的子字符串数量:
def count_substring(string):
substrings = []
for i in range(len(string)):
for j in range(i+1, len(string)+1):
if '0' not in string[i:j]:
substrings.append(string[i:j])
return len(substrings)
string = '1101111011'
print("String:", string)
print("Number of substrings with all 1's:", count_substring(string))
运行结果:
String: 1101111011
Number of substrings with all 1's: 12
在上面的程序中,我们使用了两个循环来遍历二进制字符串的所有子串。接着,我们检查每个子串是否只包含1。如果是,我们就将这个子串添加到一个列表中。最后,我们返回这个列表的长度,即为全部为1的子串数量。
让我们再来看几个示例:
string = '1010110'
print("String:", string)
print("Number of substrings with all 1's:", count_substring(string))
string = '100000'
print("String:", string)
print("Number of substrings with all 1's:", count_substring(string))
string = '1111111'
print("String:", string)
print("Number of substrings with all 1's:", count_substring(string))
运行结果:
String: 1010110
Number of substrings with all 1's: 2
String: 100000
Number of substrings with all 1's: 0
String: 1111111
Number of substrings with all 1's: 7
结论
在Python中计算二进制字符串中全部为1的子字符串数量可以通过遍历字符串并统计全1子串的数量来解决。我们只需检查每个子串是否只包含1,并将符合条件的子串添加到列表中。最后,返回这个列表的长度即为全部为1的子串数量。