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

วิธีตรวจสอบว่าลบตัวอักษร 1 ตัวแล้วความถี่ทั้งหมดเท่ากันได้ใน Python

ปัญหา

กำหนดสตริง s ตรวจสอบว่าหากลบตัวอักษรเพียง 1 ตัว จะทำให้ความถี่ของทุกตัวอักษรที่เหลือเท่ากันได้หรือไม่

ตัวอย่าง: "abbc" → ลบ 'b' 1 ตัว ได้ "abc" (ทุกตัว 1 ครั้ง) → True

แนวทางแก้ปัญหา

  1. นับความถี่เริ่มต้น หากเท่ากันทั้งหมดแล้ว คืน True
  2. ลองลดความถี่แต่ละตัวอักษรทีละ 1 แล้วตรวจสอบว่าเท่ากันทั้งหมดหรือไม่

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

from collections import defaultdict

def allSame(occurrence):
    counts = list(occurrence.values())
    return all(c == counts[0] for c in counts)

def solve(s):
    occurrence = defaultdict(int)
    for ch in s: occurrence[ch] += 1
    if allSame(occurrence): return True
    for ch in s:
        occurrence[ch] -= 1
        if allSame(occurrence): return True
        occurrence[ch] += 1
    return False

s = "abbc"
print(solve(s))  # True

อินพุต / เอาต์พุต

Input: "abbc"
Output: True