Python教程

Python刷题日记--矩阵乘法

本文主要是介绍Python刷题日记--矩阵乘法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
问题描述
  给定一个N阶矩阵A,输出A的M次幂(M是非负整数)
  例如:
  A =
  1 2
  3 4
  A的2次幂
  7 10
  15 22
输入格式
  第一行是一个正整数N、M(1<=N<=30, 0<=M<=5),表示矩阵A的阶数和要求的幂数
  接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
输出格式
  输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
样例输入
2 2
1 2
3 4
样例输出
7 10
15 22

def get_changeList(numList, size):
    list1 = [[0 for _ in range(size)] for _ in range(size)]
    for i in range(size):
        for j in range(size):
            list1[i][j] = numList[j][i]
    return list1


def get_newList(numList, list1, size):
    newList = [[0 for _ in range(size)] for _ in range(size)]
    for i in range(size):
        for j in range(size):
            newList[i][j] = sum([numList[i][k] * list1[j][k] for k in range(size)])
    return newList


if __name__ == '__main__':

    alls = input().split(" ")
    size = int(alls[0])
    times = int(alls[1])
    numList = [[int(i) for i in input().split(" ")] for _ in range(size)]
    list1 = [[0 for _ in range(size)] for _ in range(size)]

    for _ in range(times - 1):
        list1 = get_changeList(numList, size)
        numList = get_newList(numList, list1, size)
    print(numList)

这篇关于Python刷题日记--矩阵乘法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!