Как повернуть матрицу python

Поворот матрицы на 90 градусов по часовой стрелке

Поскольку в стандартной библиотеке Python подобная функция
отсутствует, надо создать собственную специальную
функцию list_rot90(data, times), способную повернуть «двумерный
список» (список списков) на 90 градусов по часовой стрелке.
Функция принимает в себя «двумерный» список (список списков) data и
количество поворотов times, которые необходимо произвести (целое
число, по умолчанию равное 1). Она должна вернуть новый
«двумерный» список (список списков).
Помогите написать предлагаемую функцию. Ничего, кроме этой
функции, в файле решения размещать не надо.

Ввод:
from solution import list_rot90
data = [[8, 2], [9, 5]]
times = 1
print(data, times)
print(list_rot90(data, times))

Поворот матрицы на 90 градусов по часовой стрелке
Непонятно как не транспонировать, а именно повернуть на 90 Дан массив N × M. Требуется.

Поворот прямоугольного массива на 90 градусов по часовой стрелке
python 3.6.4 Дан прямоугольный массив размером t*k. Поверните его на 90 градусов по часовой.

Переворот матрицы (двумерного массива) на 90 градусов по часовой стрелке
Доброго времени суток! Хотелось бы узнать больше о методе (кажется так и называется) zip. Насколько.

Повернуть массив по часовой стрелке на 90 градусов
Дан массив N × M. Требуется повернуть его по часовой стрелке на 90 градусов. Входные данные На.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
def list_rot90( data, times = 1 ): rot_data = [] for t in range( times ): m = len( data ) n = len( data[0] ) rev_data = data[ : : -1] rot_data = [ [rev_data[j][i] for j in range( m ) ] for i in range( n ) ]; data = rot_data return rot_data matrix = [ [ 8, 2 ], [ 9, 5 ] ] for s in matrix: print( *s ) print( "" ) rot_matrix = list_rot90( matrix ) for s in rot_matrix: print( *s ) print( "" ) rot_matrix2 = list_rot90( matrix, 2 ) for s in rot_matrix2: print( *s )

Лучший ответ

Сообщение было отмечено AlinaVotomina как решение

Решение

def transposed(matrix): return [[*col] for col in zip(*matrix)] def rot90: return list(map(reversed, transposed(matrix)))
def rot90(matrix): return[list(reversed(col)) for col in zip(*matrix)]

Поворот квадратной матрицы на 90 градусов по часовой стрелке, затем на 90 градусов против часовой стрелки
Поворот квадратной матрицы на 90 градусов по часовой стрелке, затем на 90 градусов против часовой.

Читайте также:  Web map service java

Поворот квадратной матрицы на 90 градусов по часовой стрелке, затем на 90 градусов против часовой стрелки
Задача: Поворот квадратной матрицы на 90 градусов по часовой стрелке, затем на 90 градусов против.

Поворот матрицы на 90 градусов по часовой стрелке
import numpy as np n = int(input(‘Количество строк = ‘)) m = int(input(‘Количество столбцов = ‘)).

Поворот матрицы на 45 градусов по часовой стрелке
Добрый день, никак не могу решить задачку: Решить поставленную задачу, используя средства.

Поворот матрицы на 90 градусов по часовой стрелке
Подскажите как повернуть двумерный массив по часовой стрелке, можно использовать другой массив либо.

Поворот матрицы на 90 градусов по часовой стрелке
заполнить матрицу целыми числами, развернуть ее на 90 градусов по часовой стрелке

Поворот матрицы на 180 градусов по часовой стрелке
Нужна программа,которая повернет квадратную матрицу из N строк и N столбцов на 180 по часовой.

Источник

numpy.flip#

Reverse the order of elements in an array along the given axis.

The shape of the array is preserved, but the elements are reordered.

axis None or int or tuple of ints, optional

Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.

If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple.

Changed in version 1.15.0: None and tuples of axes are supported

A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.

Flip an array vertically (axis=0).

Flip an array horizontally (axis=1).

flip(m, 0) is equivalent to flipud(m).

flip(m, 1) is equivalent to fliplr(m).

flip(m, n) corresponds to m[. -1. ] with ::-1 at position n.

flip(m) corresponds to m[::-1. -1. -1] with ::-1 at all positions.

Читайте также:  Выравнивание

flip(m, (0, 1)) corresponds to m[::-1. -1. ] with ::-1 at position 0 and position 1.

>>> A = np.arange(8).reshape((2,2,2)) >>> A array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.flip(A, 0) array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]]) >>> np.flip(A, 1) array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]]) >>> np.flip(A) array([[[7, 6], [5, 4]], [[3, 2], [1, 0]]]) >>> np.flip(A, (0, 2)) array([[[5, 4], [7, 6]], [[1, 0], [3, 2]]]) >>> A = np.random.randn(3,4,5) >>> np.all(np.flip(A,2) == A[. -1,. ]) True 

Источник

Как повернуть массив на 90 градусов python

Проще всего это будет сделать с помощью Numpy:

import numpy as np l = [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]] a = np.array(l) # a = array([[0, 0, 0, 0], # [0, 0, 0, 1], # [0, 0, 0, 1], # [0, 0, 0, 1]], dtype=int64) # поворот: np.rot90(a) # a = array([[0, 1, 1, 1], # [0, 0, 0, 0], # [0, 0, 0, 0], # [0, 0, 0, 0]], dtype=int64) # можно несколько раз повернуть: np.rot90(a, k=2) # a = array([[1, 0, 0, 0], # [1, 0, 0, 0], # [1, 0, 0, 0], # [0, 0, 0, 0]], dtype=int64) # "вернуть" к обычному списку списков: np.rot90(a).tolist() # => [[0, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

Соответственно для поворота по часовой стрелке используйте np.rot90(a, k=3) (270 градусов).

Если не использовать Numpy, то для поворота по часовой стрелке есть такой способ:

def transposed(matrix): return [[*col] for col in zip(*matrix)] def rot90: return list(map(reversed, transposed(matrix))) # или в одно действие def rot90(matrix): return [list(reversed(col)) for col in zip(*matrix)] 

. а для поворота против часовой:

def rot90(matrix): return [list(row) for row in list(zip(*matrix))[::-1]] 

Источник

Inplace rotate square matrix by 90 degrees | Set 1

Note: An approach that requires extra space is already discussed here.

Example no1 – Inplace rotate square matrix by 90 degrees by forming cycles:

To solve the problem follow the below idea:

To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example,
A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row, and 1st column. The second cycle is formed by the 2nd row, second-last column, second-last row, and 2nd column. The idea is for each square cycle, to swap the elements involved with the corresponding cell in the matrix in an anti-clockwise direction i.e. from top to left, left to bottom, bottom to right, and from right to top one at a time using nothing but a temporary variable to achieve this

Dry run of the above approach:

First Cycle:

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

Moving first group of four elements (elements
of 1st row, last row, 1st column and last column) of first cycle
in counter clockwise.

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

Читайте также:  Html local file src

Moving next group of four elements of
first cycle in counter clockwise

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

Moving final group of four elements of
first cycle in counter clockwise

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

Second Cycle:

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

Fixing second cycle

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

Follow the given steps to solve the problem:

  • There are N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is i
  • Consider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.
  • So run a loop in each cycle from x to N – x – 1, loop counter is y
  • The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y)
  • Print the matrix.

Below is the implementation of the above approach:

Источник

Оцените статью