使用清单和字典在Python中一起打印字谜
在本教程中,我们将编写一个程序,该程序使用list和dictionary查找和打印字谜。对于每个问题,我们都有不同的方法。尝试编写代码而不遵循本教程。如果您不能产生任何想法来编写逻辑,请执行以下步骤。
算法
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
结论
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特