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

นับคำนำหน้า (Prefixes) ที่มีความถี่ตัวอักษรมากกว่าใน Python

โจทย์: กำหนดสตริงและตัวอักษร 2 ตัว ให้หาคำนำหน้าทั้งหมดที่ตัวอักษรตัวแรกมีความถี่มากกว่าตัวที่สอง แล้วนับจำนวน

ตัวอย่าง

  • Input: string="apple", alphabets='p', 'e' → Output: ap, app, appl, apple (4 prefixes)
  • Input: string="apple", alphabets='e', 'p' → Output: 0

อัลกอริทึม

  1. วนลูปสร้าง prefix ทีละตัวอักษร
  2. นับความถี่ของตัวอักษรทั้งสองใน prefix นั้น
  3. ถ้าตัวแรกมากกว่า ให้พิมพ์ prefix นั้นและนับเพิ่ม
  4. แสดงจำนวนรวมท้ายสุด

โค้ด

def prefixes(string, char1, char2):
    count = 0
    prefix = ""
    for i in range(len(string)):
        prefix = string[:i+1]
        if prefix.count(char1) > prefix.count(char2):
            print(prefix)
            count += 1
    print(f"Total prefixes matched: {count}")

# ทดสอบ
prefixes('apple', 'p', 'e')
print("---")
prefixes('apple', 'e', 'p')

ผลลัพธ์

ap
app
appl
apple
Total prefixes matched: 4
---
Total prefixes matched: 0

สรุป

ใช้ str.count() และ string slicing แก้ปัญหาได้ตรงไปตรงมา