Python-3,印刷螺旋mxn矩阵

时间:2017-01-13 14:24:46

标签: python python-3.x matrix spiral

为什么不打印任何东西?我写的前一个矩阵nxn工作得很好。这个应该是mxn并从中间元素开始旋转。我在附加图像的纸上发布了解决方案,我认为我接近代码但它仍然没有打印。

if __name__ == "__main__":
row = int(input("Enter the number of the rows: "))
col = int(input("Enter the number of the columns: "))
matrix = []
print("Enter the values of the matrix: ")
for i in range(0, row):
    matrix.append([])
    for j in range(0, col):
        matrix[i].append(int(input()))
print("The matrix: ")
for list in matrix:
    print(list)
print("Result: ")
center = int(row/2)
row = col = center
l = 1
if row % 2 == 0 and col % 2 == 0:
while l <= center:
    while col < center + l:  #desno
        print(matrix[row][col])
        col += 1
    col -= 1
    row += 1
    while row < center + l:  #dole
        print(matrix[row][col])
        row += 1
    row -= 1
    col -= 1
while col >= center - l:  #levo
    print(matrix[row][col])
    col -= 1
col += 1
row -= 1
while row >= center - l:   #gore
    print(matrix[row][col])
    row -= 1
row += 1
col += 1
l += 1
for i in matrix[row][col:]:
    print(i)
if row % 2 != 0 and col % 2 == 0:
while l <= center:
    while col <= center + l:  # desno
        print(matrix[row][col])
        col += 1
    col -= 1
    row += 1
    while row <= center + l:  # dole
        print(matrix[row][col])
        row += 1
    row -= 1
    col -= 1
while col >= center - l:  # levo
    print(matrix[row][col])
    col -= 1
col += 1
row -= 1
while row >= center - l:  # gore
    print(matrix[row][col])
    row -= 1
row += 1
col += 1
l += 1
for i in matrix[row][col:]:
    print(i)
if row % 2 == 0 and col % 2 != 0:
while l <= center:
    while col <= center + l:  # desno
        print(matrix[row][col])
        col += 1
    col -= 1
    row += 1
    while row <= center + l:  # dole
        print(matrix[row][col])
        row += 1
    row -= 1
    col -= 1
while col >= center - l:  # levo
    print(matrix[row][col])
    col -= 1
col += 1
row -= 1
while row >= center - l:  # gore
    print(matrix[row][col])
    row -= 1
row += 1
col += 1
l += 1
for i in matrix[row][col:]:
    print(i)
if row % 2 != 0 and col % 2 != 0:
while l <= center:
    while col <= center + l:  # desno
        print(matrix[row][col])
        col += 1
    col -= 1
    row += 1
while row <= center + l:  # dole
    print(matrix[row][col])
    row += 1
row -= 1
col -= 1
while col > center - l:  # levo
    print(matrix[row][col])
    col -= 1
col += 1
row -= 1
while row > center - l:  # gore
    print(matrix[row][col])
    row -= 1
row += 1
col += 1
l += 1
for i in matrix[row][col:]:
    print(i)

Image of sketch of the solution

0 个答案:

没有答案