反转、旋转与翻转
作者:互联网
- 非原地:一维用切片,二维用list(map(list, zip(*matrix)))格式
- 原地:一维反转 - 前后交换,二维旋转 - 对角线翻转交换之后再进行一维反转
python中字符串不可变,无法原地
class ReverseInSitu:
"""
反转/旋转
"""
# 反转字符串(python字符串不可变,故不能原地反转)
@staticmethod
def reverse_str(chars: str) -> str:
if not chars:
return
return chars[::-1]
# 按单词反转字符串(python字符串不可变,故不能原地反转)
def reverse_str_by_word(self, chars: str) -> str:
if not chars:
return
chars_list = self.reverse_str(chars).split()
res = []
for s in chars_list:
res.append(self.reverse_str(s))
return ' '.join(res)
# 顺时针旋转任意二维矩阵(非原地)
@staticmethod
def rotate_any_matrix_clockwise_90(matrix: list) -> list:
if not matrix:
return
m, n = len(matrix), len(matrix[0])
try:
for i in range(m):
assert len(matrix[i]) == n # 必须是矩阵
except AssertionError:
raise
return list(map(list, zip(*matrix[::-1]))) # list(map(list, zip(*matrix))),就是\翻转
# 逆时针旋转任意二维矩阵(非原地)
def rotate_any_matrix_anti_clockwise_90(self, matrix: list) -> list:
if not matrix:
return
m, n = len(matrix), len(matrix[0])
try:
for i in range(m):
assert len(matrix[i]) == n # 必须是矩阵
except AssertionError:
raise
for i in range(m):
self.reverse_list(matrix[i])
return list(map(list, zip(*matrix))) # list(map(list, zip(*matrix[::-1]))),就是/翻转
# 原地反转一维数组
@staticmethod
def reverse_list(arr: list) -> None:
if not arr:
return
i, j = 0, len(arr)-1
while i < j:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j -= 1
# 原地顺时针旋转二维矩阵90度
def rotate_matrix_clockwise_90(self, matrix: list) -> None:
if not matrix:
return
n = len(matrix)
try:
for i in range(n):
assert len(matrix[i]) == n # 原地旋转必须行列数相等
except AssertionError:
raise
for i in range(n): # 沿\对角线翻转
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n): # 反转每行
self.reverse_list(matrix[i])
# 原地逆时针旋转二维矩阵90度
def rotate_matrix_anti_clockwise_90(self, matrix: list) -> None:
if not matrix:
return
n = len(matrix)
try:
for i in range(n):
assert len(matrix[i]) == n # 原地旋转必须行列数相等
except AssertionError:
raise
for i in range(n): # 沿/对角线翻转
for j in range(n-i):
matrix[i][j], matrix[n-j-1][n-i-1] = matrix[n-j-1][n-i-1], matrix[i][j]
for i in range(n): # 反转每行
self.reverse_list(matrix[i])
if __name__ == '__main__':
rs = ReverseInSitu()
matrix_1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
rs.rotate_matrix_clockwise_90(matrix_1)
print(matrix_1)
matrix_2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
rs.rotate_matrix_anti_clockwise_90(matrix_2)
print(matrix_2)
matrix_3 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print(rs.rotate_any_matrix_clockwise_90(matrix_3))
matrix_4 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print(rs.rotate_any_matrix_anti_clockwise_90(matrix_4))
str_1 = 'abc def gh'
print(rs.reverse_str(str_1))
str_2 = 'abc def gh'
print(rs.reverse_str_by_word(str_2))
标签:return,matrix,反转,list,len,旋转,range,str,翻转 来源: https://www.cnblogs.com/daxiacet/p/16382912.html