使用清单和字典在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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短