直接上代码了
#USTC Donglai Ma
#生成两组 六对随机字符串
#生成长度为n的字母串序列
import random
import string
def alphabetran_group(n):
stralp = ''
for i in range(n):
stralp = stralp+random.choice(string.ascii_uppercase)
return stralp
# print(alphabetran_group(25))
#生成序列 X 的长为 m,序列 Y的长为 n,序列 X 和 Y 的元素从 26个大写字母 中随机生成,m 和 n 的取值:
# 第1组: (15, 10), (15, 20), (15, 30), (15,40), (15,50), (15,60)
# 第2组: (15, 25), (30, 25), (45,25), (60,25), (75,25), (90,25)
input_fileA = open("../input/inputA.txt","w")
for i in range(10,61,10):
input_fileA.write(alphabetran_group(15)+'\n')
input_fileA.write(alphabetran_group(i)+'\n')
input_fileA.close()
input_fileB = open("../input/inputB.txt","w")
for i in range(15,91,15):
input_fileB.write(alphabetran_group(i)+'\n')
input_fileB.write(alphabetran_group(25)+'\n')
input_fileB.close()
#最长子序列算法,参照算法导论
def lcs(a,b):
lena = len(a)
lenb = len(b)
c=[[0 for i in range(lenb+1)] for j in range(lena+1)]
flag=[[0 for i in range(lenb+1)] for j in range(lena+1)]
for i in range(lena):
for j in range(lenb):
if a[i] == b[j]:
c[i+1][j+1] = c[i][j]+1
flag[i+1][j+1]= 'ok'
elif c[i+1][j]>c[i][j+1]:
c[i+1][j+1]=c[i+1][j]
flag[i+1][j+1] = 'left'
else:
c[i+1][j+1] = c[i][j+1]
flag[i+1][j+1]='up'
return c,flag
def printLcs(flag,a,i,j):
if i==0 or j==0:
return
if flag[i][j] =='ok':
printLcs(flag,a,i-1,j-1)#意味着是LCS的一个元素
print(a[i-1],end='')
elif flag[i][j]=='left':
printLcs(flag,a,i,j-1)
else:
printLcs(flag,a,i-1,j)
return
# a='ABCBDABCFGMHLS'
# b='BDCABAALGFGGSDG'
#读取文件中第n对字符串
import linecache
def read_fileA(n):
filenameA = "../input/inputA.txt"
a = linecache.getline(filenameA,2*n-1)
#b = fileA.readlines(2*n)
b = linecache.getline(filenameA,2*n)
return a,b
def read_fileB(n):
filenameB = "../input/inputB.txt"
a = linecache.getline(filenameB,2*n-1)
#b = fileA.readlines(2*n)
b = linecache.getline(filenameB,2*n)
return a,b
import time
import sys
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
def calresult_time_A(n):
a,b = read_fileA(n)
print("The result of group" +str(n) +"in file_A is ")
start = time.time()
c,flag=lcs(a,b)
end = time.time()
printLcs(flag,a,len(a),len(b))
timec = end -start
outputfile = open("../output/time.txt","a")
outputfile.write("The time of group"+str(n) +"in file_A is "+str(timec))
outputfile.close()
def calresult_time_B(n):
a,b = read_fileB(n)
print("The result of group" +str(n) +"in file_B is ")
start = time.time()
c,flag=lcs(a,b)
printLcs(flag,a,len(a),len(b))
end = time.time()
timec = end -start
outputfile = open("../output/time.txt","a")
outputfile.write("The time of group"+str(n) +"in file_B is "+str(timec)+"\n")
outputfile.close()
sys.stdout = Logger("../output/result.txt")
for i in range(1,7):
calresult_time_A(i)
calresult_time_B(i)