Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array Rotation function changing Original Array

The code is supposed to make a copy of the original array and rotate it (turn the columns into rows) while keeping the original array the same but the original array changes without a reason.

This is most likely a deep copy issue but I have tried using copy.copy() and it has not worked

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

l = [[1,2,3],[4,5,6],[7,8,9]]

def rotate(funcl):
    funcl = funcl[::-1]
    
    for s1 in range(0, len(funcl)):
        for s2 in range(s1, len(funcl)):
            funcl[s1][s2], funcl[s2][s1] = funcl[s2][s1], funcl[s1][s2]

    return funcl

print("Original Array:\n", l)
nextl = rotate(l)
print("Original Array after Function:\n", l)
print("New Rotated Array:\n", nextl)

Output:

Original Array:
 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Original Array after Function:
 [[9, 6, 3], [8, 5, 2], [7, 4, 1]]
New Rotated Array:
 [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

As you can see the function works fine but changes the original array

>Solution :

deepcopy is notoriously slow and should be avoided if you can.

zip() is frequently used to transpose lists in python. Here the only wrinkle is that you want to reverse them. You can use reversed() for this and get a very succinct:

l = [[1,2,3],[4,5,6],[7,8,9]]

def rotate(funcl):
      return list(zip(*reversed(funcl)))

print("Original Array:\n", l)
nextl = rotate(l)
print("Original Array after Function:\n", l)
print("New Rotated Array:\n", nextl)

Which prints:

Original Array:
 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Original Array after Function:
 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New Rotated Array:
 [(7, 4, 1), (8, 5, 2), (9, 6, 3)]

If it’s important to maintain inner lists rather than tuples, you can add a map to mix:

l = [[1,2,3],[4,5,6],[7,8,9]]

def rotate(funcl):
      return list(map(list, zip(*reversed(funcl))))
      # or return [list(t) for t in zip(*reversed(funcl))]

rotate(l)
# [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading