python - Python code to compute anagrams without reptetitions
问题描述
I am solving a python exercise that asks me to find all the possible anagrams of a word but excluding the anagrams that occur more then once.
Here is the code I have come up with:
from itertools import permutations
seq = getString('Insert ')
seq = permutations(seq) # this let us get all anagrams WITH repetitions
unique = []
unique2=[]
for x in seq:
unique.append(x)
i=0
while i < len(unique):
if unique[i] in unique[i+1:]:
i=i+1
continue
if unique[i] not in unique[i+1:]:
unique2.append(unique[i])
i=i+1
What the while does is basically this: consider the ith-anagram and check if in the next part of the list there is an anagram that is identical to the one we are checking. If yes, increase the counter "i" and go on, otherwise append that anagram (that we are sure it does not have repetitions) to another new list.
This goes on up until we reach an i that has a lenght equal to the lenght of the list of permutations with repetitions.
解决方案
推荐阅读
- caching - 如何将 esi 标签包含到主 esi 标签中?
- sql - 使用其他表的 Postgres 合并示例
- visual-studio-code - 如何关闭 vscode 的搜索开关?
- android - 将带有父类的可打包 Kotlin 类转换为 JSON
- c# - 使用 .NET 核心 3.1 的 Azure 网络作业
- sql - 使用 WHERE 子句中的过滤器优化 OUTER JOIN 查询。(查询规划器)
- javascript - 为什么这个 React 组件在其 prop 更改时不重新渲染?
- java - 我可以在我的 Java 代码中使用 DynamoDB Streams 来更新/添加数据到我的 DynamoDB 吗?
- javascript - 一步一步的登记表
- c++ - C++ 中三元运算符的意外行为