华为2019校招笔试题之旋转方阵(python版)

  • 说明 ?

  • 华为2019在线笔试题,现整理如下,以供之后参考
  • ? GitHub
  • 题目描述 ?

"""
题目描述: 
-- 输入一个N阶方阵(0
  • 具体代码 ?

import sys

# 输入
square_array = []
N = sys.stdin.readline().rstrip("\n")

for i in range(0, int(N)):
    row = []
    line = sys.stdin.readline().rstrip("\n")
    temp_str = line.split(" ")
    for str_ in temp_str:
        row.append(int(str_))
    square_array.append(row)

M = sys.stdin.readline().rstrip("\n")

# 旋转处理
L = int(N)
M = int(M) % 4

# 最初比较冗杂的代码
"""
# rotate_array = square_array.copy()        # 之前出错,存在二维列表的浅复制问题,一维不存在这个问题
rotate_array = [([0]*L) for i in range(L)]    # 为了避免这种情况,使用二维列表推导式
if M % 4 == 0:
    rotate_array = [item for item in square_array]

if M % 4 == 1:
    for row_ix in range(L):
        for col_ix in range(L):
            # 原矩阵逐列赋值给旋转矩阵的每一行
            rotate_array[row_ix][col_ix] = square_array[L-1-col_ix][row_ix]

if M % 4 == 2:
    for row_ix in range(L):
        for col_ix in range(L):
            # 原矩阵逐列赋值给旋转矩阵的每一行
            rotate_array[col_ix][row_ix] = square_array[L-1-col_ix][L-1-row_ix]

if M % 4 == 3:
    for row_ix in range(L):
        for col_ix in range(L):
            # 原矩阵逐列赋值给旋转矩阵的每一行
            rotate_array[row_ix][col_ix] = square_array[col_ix][L-1-row_ix]
"""
# 升级版,封装为函数,递归实现
def rotate_matrix(handled_array, order):
    rotate = [([0] * order) for _ in range(order)]
    for row_index in range(order):
        for col_index in range(order):
            # 原矩阵逐列赋值给旋转矩阵的每一行
            rotate[row_index][col_index] = handled_array[order-1-col_index][row_index]
    return rotate


rotate_array = [item for item in square_array]
for i in range(M):
    rotate_array = rotate_matrix(rotate_array, L)

# 输出
for row in rotate_array:
    row_str = ""
    for item in row:
        row_str += str(item) + " "
    print(row_str)

  • The End ??

你可能感兴趣的:(互联网笔试题,awesome,python)