算法导论之动态规划实现矩阵乘法最优括号化

先简单的上一下作业要求,便于阅读代码


image.png

直接上代码了

#USTC Donglai Ma
#参照算法导论上的源码

def maxChain(p):
    # n = len(p) - 1
    n = len(p)
    m = [[0 for i in range(n)] for j in range(n)]
    s = [[0 for i in range(n)] for j in range(n)]
    # for i in range(n):
    #     m[i][i] = 0
    for l in range(2,n):
        for i in range(1,n-l+1):
            j = i+l-1;
            m[i][j] = 9999999999;
            for k in range(i,j):
                q = m[i][k] + m[k+1][j] + p[i-1] * p[k] * p[j]
                if q < m[i][j]:
                    m[i][j] = q;
                    s[i][j] = k
    return m, s


# 输出矩阵链的最优括号化方法
def printOpt(s, i, j):
    if i == j:
        print("A", i, end='')
    else:
        # print("(", end="")
        print("(", end='')
        printOpt(s, i, s[i][j])
        printOpt(s, s[i][j]+1, j)
        print(")", end='')

# p = [7, 35, 15, 5, 10, 20, 25]
# m, s = maxChain(p)
#
# print(m)
# print(s)
# print("最优括号化方案为:")
# printOpt(s, 1, 6)
# print("")
# print("其标量乘法次数为:", m[1][6])

#生成n个随机数

import random
import numpy as np
import os

def random_int_list(start, stop, length):
    start, stop = (int(start), int(stop)) if start <= stop else (int(stop), int(start))
    length = int(abs(length)) if length else 0
    random_list = []
    for i in range(length):
        random_list.append(random.randint(start, stop))
    return random_list

#生成 并存储在input中
randomlist = random_int_list(1, 500, 50)

randomarray = np.array(randomlist)
randomarray.astype(int)

np.savetxt("../input/input.txt",randomarray,fmt="%d")

#读取n个数据并转化成list
def readlistn(n):
    alist = np.loadtxt("../input/input.txt",dtype='int')
    alist=alist.tolist()
    tosortlist = alist[0:(n-1)]
    return tosortlist

#调用计算5、10、20、30 ,随机生成 n+1 个整数值

import time
import os


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

#
# sys.stdout = Logger("yourlogfilename.txt")
# print("Hello world !") # this is should be saved in yourlogfilename.txt
import sys
def calmatrix_save(n):
    matrix = readlistn(n+2)
    start = time.time()
    m,s = maxChain(matrix)
    end = time.time()


    timec = end-start

    file_result = open("../output/result.txt","a")
    file_time = open("../output/time.txt","a")
    #这里注意输出中文的时候容易报错,因为ascii无法encode中文,这个问题要记下来
    result_str = ('\n'+"The matrix size is"+str(n)+"   "+"whose result is ")
    time_str = ("The matrix size is "+str(n)+"   "+"whose time is "+ str(timec)+'\n')

    print(result_str)
    printOpt(s,1,n)
    file_time.write(time_str)
    file_result.close()
    file_time.close()

#
sys.stdout = Logger("../output/result.txt")
#这里采用的是输出到屏幕整个再输出到
calmatrix_save(5)
calmatrix_save(10)
calmatrix_save(20)
calmatrix_save(30)

你可能感兴趣的:(算法导论之动态规划实现矩阵乘法最优括号化)