इस ट्यूटोरियल में, हम एक प्रोग्राम लिखने जा रहे हैं जो सूची का उपयोग करके एनाग्राम ढूंढता और प्रिंट करता है और शब्दकोश . हर समस्या के लिए हमारे पास अलग-अलग दृष्टिकोण हैं। ट्यूटोरियल का अनुसरण किए बिना कोड लिखने का प्रयास करें। यदि आप तर्क लिखने के लिए कोई विचार उत्पन्न करने में सक्षम नहीं हैं, तो नीचे दिए गए चरणों का पालन करें।
एल्गोरिदम
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.
आइए उपरोक्त एल्गोरिथम के लिए कोड लिखें।
उदाहरण
## 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) आउटपुट
यदि आप उपरोक्त प्रोग्राम चलाते हैं, तो आपको निम्न आउटपुट मिलेगा।
apple orange grapes pear peach
निष्कर्ष
यदि आपको ट्यूटोरियल के बारे में कोई संदेह है, तो उनका टिप्पणी अनुभाग में उल्लेख करें।