python - 概念:从 "synonyms"列表中收集 "words"

标签 python algorithm conceptual

这个问题的灵感来自:Generating a list of repetitions regardless of the order及其接受的答案:https://stackoverflow.com/a/20336020/1463143

在这里,“alphabet”是任意一组字母,例如'012' 或 'EDCRFV'

“单词”是通过对字母表进行笛卡尔积得到的。我们应该能够指定 n 来获取 n 个字母的单词。示例:

from itertools import product
alphabet = '012'
wordLen = 3
wordList = [''.join(letter) for letter in product(alphabet,repeat=wordLen)]
print wordList

给出:

['000', '001', '002', '010', '011', '012', '020', '021', '022', '100', '101', '102', '110', '111', '112', '120', '121', '122', '200', '201', '202', '210', '211', '212', '220', '221', '222']

“同义词”是通过……呃……要是我能说清楚就好了……

这些列表包含 wordList 中所有可能的“同义词”:

['000',
 '111',
 '222'] 

['001',
 '002',
 '110',
 '112',
 '220',
 '221']

['010',
 '020',
 '101',
 '121',
 '202',
 '212']

['011',
 '022',
 '100',
 '122',
 '200',
 '211']

['012',
 '021',
 '102',
 '120',
 '201',
 '210']

遗憾的是,我无法清楚地说明我是如何获得上述“同义词”列表的。我想对形成 n 个字母的单词的任意字母表执行上述操作。

最佳答案

看起来很简单:

syns = collections.defaultdict(list)

for w in wordList:
    hash = tuple(w.index(c) for c in w)
    syns[hash].append(w)

print syns.values()

关于python - 概念:从 "synonyms"列表中收集 "words",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351205/

相关文章:

python - 使用 MatPlotLib 和 Numpy 将高斯拟合到直方图 - Y 缩放错误?

python - 使用 Selenium 从网站提取 SSL 证书详细信息 - Chrome 驱动程序

algorithm - 为什么我们在计算二进制数之间的杰卡德距离时不包含 0 个匹配项?

c++ - STL 算法如何识别容器?

c# - WPF中的WPF命令和事件有什么区别?

python - 将markdown图像格式转换为html

python - 如何将cherrypy.session()存储在变量中?

database - 具有单一哈希函数的 LogLog 算法如何工作

task-parallel-library - I/O 性能 - 异步 vs TPL vs Dataflow vs RX

c# - 如何(正确)更新 WPF 应用程序的 MVVM 中的 M?