You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python是否有内置方法判断0、1字符仅分为两个连续块?

Check if Binary String Has Only Two Contiguous Blocks in Python

Hey there! Great question. Python doesn’t have a built-in method specifically for this exact check, but we can implement the logic easily with a couple of clean, efficient approaches. The goal is to verify that all '0's are grouped on one side and all '1's on the other (including edge cases like strings with only '0's or only '1's, which technically have just one block and still fit your requirement).

Approach 1: Simple Substring Transition Count

The quickest way is to count how many times the character switches between '0' and '1'. Each switch is represented by either the substring "01" or "10". If the total number of these transitions is 0 or 1, the string meets your criteria:

def has_two_blocks(binary_str):
    return binary_str.count("01") + binary_str.count("10") <= 1

Testing with your examples:

  • has_two_blocks("1010111") → returns False (3 transitions: 1→0, 0→1, 1→0)
  • has_two_blocks("111100000") → returns True (1 transition: 1→0)
  • has_two_blocks("11000111") → returns False (2 transitions: 1→0, 0→1)

This works because each substring pair represents a single block shift. Strings with all identical characters will have 0 transitions, which also passes the check.

Approach 2: Early-Exit Iteration for Large Strings

If you’re working with very long binary strings, this method is more efficient—it stops checking as soon as it detects a second transition, avoiding unnecessary processing:

def has_two_blocks(binary_str):
    if len(binary_str) <= 1:
        return True
    change_count = 0
    previous_char = binary_str[0]
    for char in binary_str[1:]:
        if char != previous_char:
            change_count += 1
            if change_count > 1:
                return False
            previous_char = char
    return True

This iterates through the string once, bailing out immediately when it finds more than one shift. It’s ideal for large inputs where performance matters.

Both approaches are straightforward and cover all edge cases (empty strings, single-character strings, all '0's, all '1's).

内容的提问来源于stack exchange,提问作者Guruku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:04