0

I am trying to convert this first multidimensional array to the second one:

[[1,4,7], [3,6,2], [2,5,9], [88,6,1]]

to

[[88,2,3,1], [6,5,6,4], [1,9,2,7]]

I wrote this function

def rotate(myList):
    newList = []
    reverseList = list(reversed(myList))
    for subList in reverseList:
        newList.append(subList[0])
    print(newList)

rotate([[1,4,7], [3,6,2], [2,5,9], [88,6,1]])

This outputs

[88, 2, 3, 1]

I reverse the multidimensional list, and for each sublist in the reversed multidimensional list, I append the first element to a new list called newList.

This is a good start, but it is not complete. How would one output the rest of the lists? I don't know how to output multiple lists to a new multidimensional list in this context.

2 Answers 2

2

zip() is your friend.

def rotate(mylist):
    return list(zip(*mylist[::-1]))

This reverses mylist, sends each sublist to zip(), and turns that into a list.

>>> rotate([[1,4,7], [3,6,2], [2,5,9], [88,6,1]])
[(88, 2, 3, 1), (6, 5, 6, 4), (1, 9, 2, 7)]
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't know about zip. This is a perfect solution. I will accept answer when time limit allows it. Thanks
I have to ask, what does the * do?
@PencilCrate - It unpacks the iterable and sends each element as a separate argument. Try print([1, 2, 3]) and print(*[1, 2, 3]).
0

You can start by creating an empty multidimensional array with the number of lines and columns you desire the output to have, and then fill it with the values of the transposition of the original matrix.

    def rotate(A, m, n):
        A = A[::-1]
        C = [[0 for j in range(n)] for i in range(m)]
        for i in range(n):
            for j in range(m):
                C[j][i] = A[i][j]
        return C

1 Comment

What's wrong with populating it on creation? And you should probably keep the same method signature, and just calculate m and n automatically. def rotate(A): return [[A[::-1][j][i] for j in range(len(A))] for i in range(len(A[0]))].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.