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

โปรแกรมตรวจสอบว่าประโยคเป็น pangram หรือไม่ด้วย Python


สมมติว่าเรามีประโยค s ที่มีแต่ตัวอักษรพิมพ์เล็กภาษาอังกฤษ เราต้องตรวจสอบว่ามันเป็น pangram หรือไม่ พังแกรมคือสตริงที่มีตัวอักษรทั้ง 26 ตัวครบ

เช่น s = "thegrumpywizardmakestoxicbrewfortheevilqueenandjack" ผลลัพธ์คือ True เพราะมี a-z ครบ 26 ตัว

ขั้นตอนการแก้ปัญหา

  • dictb = {} (dictionary นับจำนวนตัวอักษร)
  • วนลูปแต่ละ i ใน s: dictb[i] = dictb.get(i, 0) + 1
  • ถ้า len(dictb) == 26: คืน True
  • มิฉะนั้น: คืน False

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

def solve(s):
    dictb = {}
    for i in s:
        dictb[i] = dictb.get(i, 0) + 1
    if len(dictb) == 26:
        return True
    return False

s = "thegrumpywizardmakestoxicbrewfortheevilqueenandjack"
print(solve(s))

ข้อมูลเข้า

"thegrumpywizardmakestoxicbrewfortheevilqueenandjack"

ข้อมูลออก

True