【发布时间】:2017-03-18 21:22:09
【问题描述】:
我正在尝试编写一个 python 程序来找到最接近单词的回文。我可以在字符串的任何部分添加一个字母,从字符串的任何部分删除一个字母,或者在字符串的任何部分更改一个字母。我一直在研究使用 levenshtein 距离来找到帖子Edit Distance in Python 中两个单词之间所需的最少编辑次数。但我不确定如何以编程方式找到需要最少编辑次数的回文。我正在努力实现的一些示例:
palindrome('hello') = 'ollo'
#you can remove the h and then turn the e into an o, giving a palindrome in 2 steps
levenshtein('hello',palindrome('hello')) = 2
palindrome('test') = 'tet'
#you can remove the s to get a palindrome
levenshtein('test',palindrome('test')) = 1
palindrome('tart') = 'trart'
#adding an r or removing the r produces a palindrome, but both solutions only require 1 edit so either would be acceptable.
levenshtein('tart',palindrome('tart')) = 1
我能够使用链接帖子中的 levenshtein 代码来查找两个字符串之间的距离。我需要帮助编写一个回文()函数,该函数接受一个字符串并返回最接近该字符串的回文。
【问题讨论】:
-
在最坏的情况下,您应该能够从字符串的任何一个字母子串构造回文。也许从那里开始,在原始字符串 o 中的字母之间迭代,将 o 分成两部分 o1 和 o2 , 或者有两个字符的最小长度。然后在将惩罚(编辑距离)分配给插入或删除的两个片段之间进行序列比对。将编辑距离和类型与子串 o1 和 o2 的长度进行比较,以决定如何构造回文。
标签: python algorithm palindrome