-3

I am trying to swap local variables within a function to rotate a 2 by 2 matrix by 90 degrees.

def twobytwo(m):
    last = len(m)-1
    for i in range(0, last):
        swap(m[i][i], m[i][last])
        swap(m[i][i], m[last][last])
        swap(m[i][i], m[last][i])
    return m


def swap(i, j):
    temp = i
    i = j
    j = temp

print(twobytwo([[0, 1], [2, 3]]))

Currently, I am returned the original matrix but I want to see

[[2,0],[3,1]]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
stillearning
  • 393
  • 2
  • 15

2 Answers2

1

I think this is what you want to achieve:

def twobytwo(m):
    last = len(m)-1
    for i in range(0, last):
        m[i][i], m[i][last] = m[i][last], m[i][i]
        m[i][i], m[last][last] = m[last][last], m[i][i]
        m[i][i], m[last][i] = m[last][i], m[i][i]
    return m

print(twobytwo([[0, 1], [2, 3]]))

EDIT: If you still want to maintain the function swap:

def swap(i, j):
    return j, i

a, b = swap(a, b)

But I think a, b = b, a is good enough.

keineahnung2345
  • 2,635
  • 4
  • 13
  • 28
0

Your assumption is that the swap() parameters are modified in place (i.e. pass-by-reference). Python does not do that in your code: when you call something like swap(m[i][i], m[i][last]), it dereferences the values of m and calls swap(0,1). So swap() only modifies i,j; it does not modify your "matrix" (which technically is a list of lists).

Try rewriting your swap() function to take the "matrix" plus two pairs of indices: (i,j) and (k,l).

Greg Glockner
  • 5,433
  • 2
  • 20
  • 23
  • Python does also not use "pass by value". See https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference/986145#986145 – mkrieger1 Jan 18 '19 at 00:43
  • @mkrieger1 : That would be true if you pass an object like m, but the sample code dereferences to int values, which are not objects. Nevertheless, I updated my answer to clear this up. – Greg Glockner Jan 18 '19 at 01:06