Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để tìm kích thước của tập con lớn nhất của các từ đảo chữ

Cho một mảng chữ thường. Nhiệm vụ của chúng tôi là tìm kích thước của tập hợp con lớn nhất của chuỗi được đảo chữ của nhau. Đảo chữ của chuỗi có nghĩa là một chuỗi là đảo chữ của chuỗi khác nếu chuỗi thứ hai chỉ đơn giản là sự sắp xếp lại của chuỗi đầu tiên. Ở đây, chúng ta có thể giải quyết vấn đề này một cách nhanh chóng trong python bằng phương thức Counter ().

Ví dụ:các chuỗi 'python' và 'typhon' là các từ đảo ngữ.

Thuật toán

Step 1: Split input string separated by space into words.
Step 2: Sort each string in given list of strings.
Step 3: Now create dictionary using counter method which will have strings as key and their Frequencies as value.
Step 4: Get maximum value of frequency using max function.

Mã mẫu

# Function to find the size of largest subset
# of anagram words
from collections import Counter

def largestana(str1):
   # split input string separated by space
   str1 = str1.split(" ")

   # sort each string in given list of strings
   for i in range(0,len(str1)):
   str1[i]=''.join(sorted(str1[i]))

   # now create dictionary using counter method
   # which will have strings as key and their
   # frequencies as value
   newstr1 = Counter(str1)

   # get maximum value of frequency
   print ("The Size Of largest subset of Anangram word is ::>",max(newstr1.values()))

   # Driver program
   if __name__ == "__main__":
      str1 = input("Enter the string ::>")
largestana(str1)

Đầu ra

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