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

โปรแกรม Python หาขนาด subset ใหญ่สุดของคำอะนาแกรม


กำหนดอาร์เรย์ตัวพิมพ์เล็ก หาขนาด subset ใหญ่สุดที่เป็นอะนาแกรม (anagram) กัน โดยใช้ collections.Counter

ตัวอย่าง

Input: qwe ewq rty ytr ytr ytr
Output: 4 (ytr, ytr, ytr, rty เป็นอะนาแกรมกัน)

อัลกอริทึม

  1. แยกสตริงด้วย space เป็นคำ
  2. เรียงตัวอักษรแต่ละคำ
  3. สร้าง Counter นับความถี่
  4. หาค่าสูงสุด

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

from collections import Counter

def largestana(str1):
    str1 = str1.split(" ")
    for i in range(len(str1)):
        str1[i] = ''.join(sorted(str1[i]))
    newstr1 = Counter(str1)
    print("The Size Of largest subset of Anagram word is:", max(newstr1.values()))

if __name__ == "__main__":
    str1 = input("Enter the string: ")
    largestana(str1)

ผลลัพธ์

Enter the string: qwe ewq rty ytr ytr ytr
The Size Of largest subset of Anagram word is: 4