(python)最长公共子序列递归算法、动态规划算法比较实验
实验题目
最长公共子序列递归算法、动态规划算法比较实验
实验要求
画出运行时间与n变化曲线对比图,并分析原因
实验目的
1、 掌握递归算法与动态规划算法思想。
2、 编写实现最长公共子序列的递归算法及动态规划算法。
3、 比较递归算法与动态规划算法解决最长公共子序列问题不同n值所耗费的时间。
实验步骤
1、随机生成指定长度的字符串,默认字符串长度为16
#生成一个指定长度的随机字符串
def generate_random_str(randomlength=16):
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
length = len(base_str) - 1
for i in range(randomlength):
random_str += base_str[random.randint(0, length)]
return random_str
2、递归算法解决最长公共子序列问题
#递归算法求最长公共子序列长度
def rec_LCS(i,j):
lena = len(a)
lenb = len(b)
if i>=lena or j>=lenb:
return 0
if a[i]==b[j]:
return 1+rec_LCS(i+1,j+1)
elif rec_LCS(i+1,j)>rec_LCS(i,j+1):
return rec_LCS(i+1,j)
else:
return rec_LCS(i,j+1)
3、动态规划算法解决最长公共子序列问题
#动态规划求最长公共子序列长度
def LCS(string1,string2):
len1 = len(string1)
len2 = len(string2)
book = [[0 for i in range(len1+1)] for j in range(len2+1)]
for i in range(1,len2+1):
for j in range(1,len1+1):
if string2[i-1] == string1[j-1]:
book[i][j] = book[i-1][j-1]+1
else:
book[i][j] = max(book[i-1][j],book[i][j-1])
return book[-1][-1]
4、统计函数运行时间
#函数运算时间
def time_Counter(func, x, y):
time_start = time.time()
func(x,y)
time_end = time.time()
return time_end-time_start
5、可视化显示实验结果
def ShowTimes(N,time1, time2):
#设置汉字格式
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.figure("Lab5-最长公共子序列")
plt.title(u'递归与动态规划解决最长公共子序列问题所耗费的时间',FontProperties=font)
plt.xlabel(u'n值',FontProperties=font)
plt.ylabel(u'所需时间(s)',FontProperties=font)
plt.scatter(x=N, y=time1, color='black',s=10)
plt.scatter(x=N, y=time2, color='red',s=10)
plt.plot(N,time1,color='black')
plt.plot(N,time2,color='red')
for a,b in zip(N,time1):
plt.text(a, b+0.3,'%.2fs' % b)
for a,b in zip(N,time2):
plt.text(a, b+0.1,'%.2fs' % b,color = 'red')
rec_LCS = mlines.Line2D([], [], color='black', marker='.',
markersize=10, label='rec_LCS')
LCS = mlines.Line2D([], [], color='red', marker='.',
markersize=10, label='LCS')
plt.legend(handles=[rec_LCS,LCS]
plt.show()
6、主函数设计
if __name__=='__main__':
N = []
time1 = []
time2 = []
for i in range(1,10,1):
a = generate_random_str(i)
b = generate_random_str(i)
#time1.append(1)
time1.append(time_Counter(rec_LCS,0,0))
time2.append(time_Counter(LCS,a,b))
N.append(i)
ShowTimes(N,time1,time2)
#算法测试
a = generate_random_str(10)
b = generate_random_str(10)
print('字符串a:',a)
print('字符串b:',b)
print('递归算法求得的最长公共子序列长度:',rec_LCS(0,0))
print('动态规划算法求得的最长公共子序列长度:',LCS(a,b))
print('递归实现最长公共子序列算法所耗时间:',time1)
print('动态规划实现最长公共子序列算法所耗时间:',time2)
7、输出实验结果
全部实验代码
import time
import random
import sys
sys.setrecursionlimit(1000000)
from matplotlib.font_manager import FontProperties
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
#递归算法求最长公共子序列长度
def rec_LCS(i,j):
lena = len(a)
lenb = len(b)
if i>=lena or j>=lenb:
return 0
if a[i]==b[j]:
return 1+rec_LCS(i+1,j+1)
elif rec_LCS(i+1,j)>rec_LCS(i,j+1):
return rec_LCS(i+1,j)
else:
return rec_LCS(i,j+1)
#动态规划求最长公共子序列长度
def LCS(string1,string2):
len1 = len(string1)
len2 = len(string2)
book = [[0 for i in range(len1+1)] for j in range(len2+1)]
for i in range(1,len2+1):
for j in range(1,len1+1):
if string2[i-1] == string1[j-1]:
book[i][j] = book[i-1][j-1]+1
else:
book[i][j] = max(book[i-1][j],book[i][j-1])
return book[-1][-1]
#函数运算时间
def time_Counter(func, x, y):
time_start = time.time()
func(x,y)
time_end = time.time()
return time_end-time_start
#生成一个指定长度的随机字符串
def generate_random_str(randomlength=16):
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
length = len(base_str) - 1
for i in range(randomlength):
random_str += base_str[random.randint(0, length)]
return random_str
def ShowTimes(N,time1, time2):
#设置汉字格式
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
plt.figure("Lab5-最长公共子序列")
plt.title(u'递归与动态规划解决最长公共子序列问题所耗费的时间',FontProperties=font)
plt.xlabel(u'字符串长度',FontProperties=font)
plt.ylabel(u'所需时间(s)',FontProperties=font)
plt.scatter(x=N, y=time1, color='black',s=10)
plt.scatter(x=N, y=time2, color='red',s=10)
plt.plot(N,time1,color='black')
plt.plot(N,time2,color='red')
for a,b in zip(N,time1):
plt.text(a, b+0.3,'%.2fs' % b)
for a,b in zip(N,time2):
plt.text(a, b+0.1,'%.2fs' % b,color = 'red')
rec_LCS = mlines.Line2D([], [], color='black', marker='.',
markersize=10, label='rec_LCS')
LCS = mlines.Line2D([], [], color='red', marker='.',
markersize=10, label='LCS')
plt.legend(handles=[rec_LCS,LCS])
plt.show()
if __name__=='__main__':
N = []
time1 = []
time2 = []
for i in range(1,10,1):
a = generate_random_str(i)
b = generate_random_str(i)
#time1.append(1)
time1.append(time_Counter(rec_LCS,0,0))
time2.append(time_Counter(LCS,a,b))
N.append(i)
ShowTimes(N,time1,time2)
#算法测试
a = generate_random_str(10)
b = generate_random_str(10)
print('字符串a:',a)
print('字符串b:',b)
print('递归算法求得的最长公共子序列长度:',rec_LCS(0,0))
print('动态规划算法求得的最长公共子序列长度:',LCS(a,b))
print('递归实现最长公共子序列算法所耗时间:',time1)
print('动态规划实现最长公共子序列算法所耗时间:',time2)