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

การตรวจสอบ Anagram ใน Python ด้วย collections.Counter()

สองสตริงถือว่าเป็น anagram กันเมื่อมีตัวอักษรเหมือนกันหมด แม้จะเรียงต่างกัน ในบทช่วยสอนนี้ เราจะตรวจสอบ anagram ใน Python โดยใช้เมธอด collections.Counter()

ตัวอย่าง

Input: string_one = "cat" string_two = "tac"
Output: True

collections.Counter()

collections.Counter() คืนค่าเป็น Dictionary ที่เก็บความถี่ของแต่ละตัวอักษรในสตริง ออบเจ็กต์ Counter มีเมธอดต่างๆ เช่น most_common(), หาตัวอักษรที่ไม่ซ้ำ, นับจำนวน ฯลฯ

ตัวอย่างการใช้งาน Counter

import collections

# creating Counter object
counter = collections.Counter("Hafeez")

# printing the counter
print(counter)

# displaying most common character
print("\nMost common character")
print(counter.most_common(1))

ผลลัพธ์

Counter({'e': 2, 'H': 1, 'a': 1, 'f': 1, 'z': 1})
Most common character
[('e', 2)]

ขั้นตอนตรวจสอบ Anagram

อัลกอริทึม

1. กำหนดสตริง 2 ตัว
2. สร้าง collections.Counter() objects สำหรับทั้งสองสตริง
3. ถ้าทั้งสอง objects เท่ากัน
     3.1 พิมพ์ True
   มิฉะนั้นพิมพ์ False

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

import collections

# initializing strings
string_one = "cat"
string_two = "atc"

# checking the Counter objects of both strings
if collections.Counter(string_one) == collections.Counter(string_two):
    # they are equal so, printing True
    print(True)
else:
    # they are not equal so, printing False
    print(False)

ผลลัพธ์

True

สรุป

การใช้ collections.Counter() ทำให้การตรวจสอบ anagram ง่ายและกระชับ เพราะเปรียบเทียบความถี่ตัวอักษรโดยตรง หากมีปัญหาในการทำตามบทช่วยสอน สามารถถามได้ในส่วนความคิดเห็น