Short Python


  • 1

    One using iterator.

    class Solution(object):
        def matrixReshape(self, nums, r, c):
            """
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            """
            A = (x for row in nums for x in row)
            return [[next(A) for i in range(c)] for j in range(r)] \
                    if c * r == len(nums) * len(nums[0]) else nums
    

    And the other using list to store all num in nums.

    class Solution(object):
        def matrixReshape(self, nums, r, c):
            """
            :type nums: List[List[int]]
            :type r: int
            :type c: int
            :rtype: List[List[int]]
            """
            A = [x for row in nums for x in row]
            return [A[i*c:(i+1)*c] for i in range(r)] if c * r == len(A) else nums
    

  • 0

    Generator expressions already return iterators, so you don't need the iter.


  • 0

    @StefanPochmann
    Thanks for point that out.


Log in to reply
 

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