【发布时间】:2015-11-22 20:29:07
【问题描述】:
我正在尝试在 Python 中解决Longest Common Subsequence。我已经完成了它,它工作正常,虽然我已经提交了它,它说它已经部分完成了 50%。我不确定我在这里缺少什么,不胜感激。
挑战说明:
给你两个序列。编写一个程序来确定两个字符串之间的最长公共子序列(每个字符串的最大长度为 50 个字符)。注意:此子序列不必是连续的。输入文件可能包含空行,这些需要忽略。
输入样本:
第一个参数是文件名的路径,每行包含两个字符串,分号分隔。您可以假设每个测试用例只有一个唯一的子序列。例如:
XMJYAUZ;MZJAWXU
输出样本:
最长的公共子序列。确保打印的每一行都没有尾随空格。例如:
MJAU
我的代码是
# LONGEST COMMON SUBSEQUENCE
import argparse
def get_longest_common_subsequence(strings):
# here we will store the subsequence list
subsequences_list = list()
# split the strings in 2 different variables and limit them to 50 characters
first = strings[0]
second = strings[1]
startpos = 0
# we need to start from each index in the first string so we can find the longest subsequence
# therefore we do a loop with the length of the first string, incrementing the start every time
for start in range(len(first)):
# here we will store the current subsequence
subsequence = ''
# store the index of the found character
idx = -1
# loop through all the characters in the first string, starting at the 'start' position
for i in first[start:50]:
# search for the current character in the second string
pos = second[0:50].find(i)
# if the character was found and is in the correct sequence add it to the subsequence and update the index
if pos > idx:
subsequence += i
idx = pos
# if we have a subsequence, add it to the subsequences list
if len(subsequence) > 0:
subsequences_list.append(subsequence)
# increment the start
startpos += 1
# sort the list of subsequences with the longest at the top
subsequences_list.sort(key=len, reverse=True)
# return the longest subsequence
return subsequences_list[0]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
# read file as the first argument
with open(args.filename) as f:
# loop through each line
for line in f:
# if the line is empty it means it's not valid. otherwise print the common subsequence
if line.strip() not in ['\n', '\r\n', '']:
strings = line.replace('\n', '').split(';')
if len(strings[0]) > 50 or len(strings[1]) > 50:
break
print get_longest_common_subsequence(strings)
return 0
if __name__ == '__main__':
main()
【问题讨论】:
-
最长公共子序列不是
MJAU它的XMJAUZ -
不是真的,这不是一个序列。示例在挑战描述中给出,不是我的结果。
-
那就不清楚了。鉴于这对:
XMJYAUZ;MZJAWXU你说最长的公共子序列是MJAU并且你还说:“这个子序列不需要是连续的”。这是不正确的,因为X和Z也很常见。其实MJAU也不是连续子序列。
标签: python python-2.7