旋转矩阵的Python程序。为什么我的课程花了这么多时间?

时间:2015-10-08 05:54:15

标签: python matrix time-complexity

我在Python 2.7中编写了这个程序,它显示了一些测试用例的运行时错误,并且对某些测试用例花费了10秒以上。我是编码的新手,无法弄清楚为什么花了这么多时间。

该程序用于逆时针旋转矩阵元素。

Input
4 4 1

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Output
2 3 4 8 
1 7 11 12 
5 6 10 16 
9 13 14 15 

第一个输入是No of Rows(M),No of Columns(N),No of rotation(R)。 然后逐行输入矩阵的元素。输出显示旋转。较小的M和N将始终是均匀的。

enter image description here

这是我的计划:

def printAsNeeded(matrix):
    length = len(matrix)
    n = len(matrix[0])
    for i in range(length):
        a = str()
        for j in range(n):
            a = a+str(matrix[i][j])+' '
        print a

def rotate(matrix):
    count = 0
    M = len(matrix)
    N = len(matrix[0])
    rmatrix = []
    for i in range(M):
        rmatrix.append([])
        for j in range(N):
            rmatrix[i].append(0)
    if(M<N):
       mag = M/2
    else:
       mag = N/2
    #down: 
    for i in range(mag):
        for j in range(count, M - (count+1)):
            rmatrix[j+1][i] = matrix[j][i]
        count = count+1
    count = 0
    #up
    for i in range(N-1, mag-1, -1):
        for j in range(count, M - (count+1)):
            rmatrix[j][i] = matrix[j+1][i]
        count = count+1
    count = 0
    #right
    for i in range(M-1, mag-1, -1):
        for j in range(count, N - (count+1)):
            rmatrix[i][j+1] = matrix[i][j]
        count = count+1
    count = 0
    #left
    for i in range(mag):
        for j in range(count, N - (count+1)):
            rmatrix[i][j] = matrix[i][j+1]
        count = count+1
    count = 0


    return rmatrix


M, N, R = raw_input().split()
M = int(M) #No of rows
N = int(N) #No of columns
R = int (R) #No of rotations
omatrix = []

for i in range(M):
    omatrix.append([])
    data = raw_input().split()
    for j in range(len(data)):
        omatrix[i].append(int(data[j]))

def matrixRotation(matrix, n):
    for i in range(n):
        matrix = rotate(matrix)
    printAsNeeded(matrix)

matrixRotation(omatrix, R)

1 个答案:

答案 0 :(得分:1)

对于方阵,您的算法有O(M * M * R) complexity。这很容易看出:

def matrixRotation(matrix, n):
    for i in range(n):
        matrix = rotate(matrix)  # number of cycles = R

def rotate(matrix):
    mag = M/2
    count = 0
    for i in range(mag):  # number of cycles ~ M
        for j in range(count, M - (count+1)):  # number of cycles ~ M
            rmatrix[j+1][i] = matrix[j][i]
        count = count+1

因此,总步数增长得非常快,对于100x旋转的1000x1000矩阵,您将需要执行~100M步骤。

发明更好的算法超出了这个问题的范围(在现实生活中,无论如何都会使用NumPy)。但我看到的一个明显的初学者错误是您使用range而不是xrange。在这种情况下效率非常低,因为您每次都会创建一个临时列表。