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

Sử dụng Counter () trong Python 3.x. để tìm loại bỏ ký tự tối thiểu để tạo hai chuỗi đảo chữ

Trong bài viết này, chúng ta sẽ tìm hiểu về cách chúng ta có thể tạo một chuỗi thành một pangram bằng cách sử dụng hàm counter () trong Python 3.x. Hoặc sớm hơn. Để làm như vậy, chúng tôi được phép xóa bất kỳ ký tự nào khỏi chuỗi đầu vào. Chúng tôi cũng sẽ tìm số lượng các ký tự bắt buộc như vậy cần được loại bỏ để biến chuỗi thành một chữ cái đảo ngữ.

Hai chuỗi được cho là đảo chữ của nhau khi chúng chứa cùng một loại bảng chữ cái theo bất kỳ thứ tự ngẫu nhiên nào.

Phương thức counter () hiện diện trong mô-đun thu thập có sẵn bằng Python. Điều kiện tiên quyết là nhập mô-đun bộ sưu tập để sử dụng hàm counter ().

Thuật toán

1. Conversion of input string into a dictionary type having characters as
keys and their frequency as values using Counter(inp_str) available in
the collections module.
2. Counting the total number of keys and counting the number of keys in
common to both dictionaries converted from input strings.
3. If no common keys are detected this means there is a need for removal
of (sum of the length of both dictionaries) characters from both the
input strings.
4. otherwise (max(length of both dictionaries) – number of Common keys
available ) will give the required number of characters to be removed

bộ sưu tập. Bộ đếm là một lớp con của từ điển để đảm bảo tự động đếm các chữ cái bởi trình thông dịch. Chúng tôi thực sự không cần tạo các chuỗi con hoặc kiểm tra xem chúng có phải là các ký tự đảo ngữ theo cách thủ công hay không.

Ví dụ

# two strings become anagram
from collections import Counter
def convertAnagram(str_1, str_2):
   # conversion of strings to dictionary type
   dict_1 = Counter(str_1)
   dict_2 = Counter(str_2)
   keys_1 = dict_1.keys()
   keys_2 = dict_2.keys()
   # count number of keys in both lists of keys
   count_1 = len(keys_1)
   count_2 = len(keys_2)
   # convert pair of keys into set to find common keys
   set_1 = set(keys_1)
   commonKeys = len(set_1.intersection(keys_2))
   if (commonKeys == 0): # no common things found i.e. all are distinct
      return (count_1 + count_2)
   else: # some elements are already matching in input
      return (max(count_1, count_2)-commonKeys)
str_1 ='Tutorials'
str_2 ='sTutalori'
str_3='Point'
print (convertAnagram(str_1, str_2))
print (convertAnagram(str_3, str_2))

Đầu ra

0
6

Kết luận

Trong bài viết này, chúng ta đã học cách có thể tạo hai chuỗi đảo chữ của nhau bằng cách đếm số ký tự cần thiết để duy trì mối quan hệ đảo chữ trong Python 2.x. cần thiết.