#๐Ÿ”’ Reverse individual rows in matrix in place without reversing entire matrix

17 messages ยท Page 1 of 1 (latest)

turbid cloak
#

In a 2d matrix, I want to reverse each row in matrix without changing order of rows.

example: I have a matrix [[1,2,3], [4,5,6], [7,8,9]]
If i use python reverse function, it becomes [[9,8,7], [6,5,4], [3,2,1]]
Instead my desired result is [[3,2,1], [6,5,4], [9,8,7]]

We can use small code snippet like

     row.reverse()

But is there a way to incorporate this in reverse function only? Sorry if this is a dumb question, i am not very good with programming

loud cargoBOT
#

@turbid cloak

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

austere hawk
#

You might be interested to look at Numpy.

#

Otherwise, addressing each row object and calling each's reverse method might be the best approach, as you've done.

#

!e py import numpy as np arr = np.arange(1, 10).reshape(3, 3) print(arr) arr = arr[:, ::-1] print(arr)

loud cargoBOT
turbid cloak
austere hawk
#

It can be.

#

!e py import numpy as np arr = np.arange(1, 10).reshape(3, 3) print(arr, id(arr)) arr[:] = arr[:, ::-1] print(arr, id(arr))

loud cargoBOT
austere hawk
#

There's probably some named method, even. I'll just check.

turbid cloak
#

reversed will return a new copy too i guess

#

reverse is the best way so far

austere hawk
#

!e py import numpy as np arr = np.arange(1, 10).reshape(3, 3) arr[:] = np.flip(arr, 1) print(arr)

loud cargoBOT
loud cargoBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.