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

In các từ đảo ngữ cùng nhau trong Python bằng Danh sách và Từ điển

Trong hướng dẫn này, chúng tôi sẽ viết một chương trình tìm và in các ký tự đảo ngữ bằng cách sử dụng danh sách từ điển . Chúng tôi có những cách tiếp cận khác nhau cho mọi vấn đề. Cố gắng viết mã mà không làm theo hướng dẫn. Nếu bạn không thể tạo ra bất kỳ ý tưởng nào để viết logic, hãy làm theo các bước dưới đây.

Thuật toán

1. Initialize a list of strings.
2. Initialize an empty dictionary.
3. Iterate through the list of strings.
   3.1. Sort the string and check if it is present in the dictionary as key or not.
      3.1.1. If the sorted string is already present dictionary as a key then, append the original string to the key.
   3.2 Else map an empty list with the sorted string as key and append the original to it.
4. Initialize an empty string.
5. Iterate through the dictionary items.
   5.1. Concatenate all the values to the empty string.
6. Print the string.

Hãy viết mã cho thuật toán trên.

Ví dụ

## initializing the list of strings
strings = ["apple", "orange", "grapes", "pear", "peach"]
## initializing an empty dictionary
anagrams = {}
## iterating through the list of strings
for string in strings:
   ## sorting the string
   key = "".join(sorted(string))
      ## checking whether the key is present in dict or not
      if string in anagrams.keys():
         ## appending the original string to the key
         anagrams[key].append(string)
      else:
         ## mapping an empty list to the key
         anagrams[key] = []
         ## appending the string to the key
         anagrams[key].append(string)
## intializing an empty string
result = ""
## iterating through the dictionary
for key, value in anagrams.items():
   ## appending all the values to the result
   result += "".join(value) + " "
## printing the result
print(result)

Đầu ra

Nếu bạn chạy chương trình trên, bạn sẽ nhận được kết quả sau.

apple orange grapes pear peach

Kết luận

Nếu bạn có bất kỳ nghi ngờ nào về hướng dẫn này, hãy đề cập đến chúng trong phần bình luận.