My 70 ms python solution


  • 0
    M
    class Solution:
        # @param matrix, a list of lists of integers
        # @return nothing (void), do not return anything, modify matrix in-place instead.
        def rotate(self, matrix):
            matrix[:] = zip(*matrix[::-1])
            matrix[:] = [list(element) for element in matrix ]
    

    from peter Norvig's blog: check out the following question :

    http://norvig.com/python-iaq.html

    Q: Hey, can you write code to transpose a matrix in 0.007KB or less?

    I thought you'd never ask. If you represent a matrix as a sequence of sequences, then zip can do the job:

    m = [(1,2,3), (4,5,6)]
    zip(*m)
    [(1, 4), (2, 5), (3, 6)]

    To understand this, you need to know that f(*m) is like apply(f, m). This is based on an old Lisp question, the answer to which is Python's equivalent of map(None,*m), but the zip version, suggested by Chih-Chung Chang, is even shorter. You might think this is only useful for an appearance on Letterman's Stupid Programmer's Tricks, but just the other day I was faced with this problem: given a list of database rows, where each row is a list of ordered values, find the list of unique values that appear in each column. So I wrote:

    possible_values = map(unique, zip(*db))


  • 0
    S
    class Solution:
        # @param {integer[][]} matrix
        # @return {void} Do not return anything, modify matrix in-place instead.
        def rotate(self, matrix):
            matrix[:] = list(zip(*matrix[::-1]))
    

    list comprehension is not necessary.


  • 0

    No, yours is pointless. zip already returns a list. What @mindheist does is turn the tuples inside the list into lists.

    You're right about list comprehension being unnecessary, though, and it's better done as map(list, zip(*A[::-1])).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.