Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่า Binary String จัดเรียงเป็น 0101... ได้หรือไม่ด้วย Python


สมมติ Binary String s ความยาว >= 2 ต้องเช็คว่าเรียงใหม่เป็น Alternating 0/1 ได้หรือไม่

เช่น Input s = "1000111" Output True (จัดเป็น "1010101")

ขั้นตอนแก้:

  • one_count = count('1'), zero_count = count('0')
  • ถ้าความยาวคู่: one_count == zero_count
  • ถ้าความยาวคี่: |one_count - zero_count| == 1

ตัวอย่างโค้ด

def solve(s):
    one_count = s.count('1')
    zero_count = s.count('0')
    if len(s) % 2 == 0:
        return (one_count == zero_count)
    return abs(one_count - zero_count) == 1

s = "1000111"
print(solve(s))

Input

"1000111"

Output

True