当前位置:   article > 正文

(python)最长公共子序列递归算法、动态规划算法比较实验_最长公共子序列递归备忘录,动态规划算法比较

最长公共子序列递归备忘录,动态规划算法比较

(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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

4、统计函数运行时间

#函数运算时间
def time_Counter(func, x, y):
    time_start = time.time()
    func(x,y)
    time_end = time.time()
    return time_end-time_start
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/201898
推荐阅读
相关标签
  

闽ICP备14008679号