In Python, can it be more concise?


  • 33
    A
    def maxProduct(nums):
        maximum=big=small=nums[0]
        for n in nums[1:]:
            big, small=max(n, n*big, n*small), min(n, n*big, n*small)
            maximum=max(maximum, big)
        return maximum

  • -12
    D
    This post is deleted!

  • 0
    S

    Well, your "one line" of code is 30 characters above 80. Personally, I'll take five readable lines over something I have to scroll to read any day :).


  • 3
    M

    @stevenhelferich @AceSmg Okay when I do:

    def maxProduct(self,nums):
            maximum=big=small=nums[0]
            for n in nums[1:]:
                big = max(n, n*big, n*small) 
                small = min(n, n*big, n*small)
                maximum=max(maximum, big)
            return maximum
    

    It gives me wrong answer on input [-4, -3, -2] !! Any idea why? Weird.


  • 3
    Y

    @modqhx you calculate 'big' then use that updated value to calculate 'small'. But the calculation of 'small' should refer to the previous 'big' value. Better to do as @AceSmg on one line. Or else you need to track the previous values in each iteration.


  • 1
    V

    '''
    This seems to work. You had to work on the previous big values but instead used the updated one.

    class Solution(object):
    def maxProduct(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """

        maxim = big = small = nums[0]
        for n in nums[1:]:
            l_big = max(n, n*big, n*small)
            l_small = min(n, n*big, n*small)
            big = l_big
            small = l_small
            maxim = max(maxim,big)
        return maxim
    

    '''


  • 1

    @modqhx

    It is not wired at all. Actually it is how python works.
    The code below

    #Code 1
    big = max(n, n*big, n*small) 
    small = min(n, n*big, n*small)
    

    does not equal to the code below:

    #Code 2
    big, small=max(n, n*big, n*small), min(n, n*big, n*small)
    

    In Code 2: the big and small got calculated and assigned a new value at the same time.
    But in Code 1: the small got calculated and assigned a new value based on the new "big".
    In your [-4,-3,-2] example:

    when n = 1:
    Code 1:

    big = max(n, n*big, n*small)    
    # which is  max( (-3), (-3)*(-4), (-3)*(-4)) = 12
    small = min(n, n*big, n*small)
    # which is min( (-3), (-3)*12, (-3)*(-4)) = -36
    

    it is easy to see when n ==2, the max value will be 72 instead of 72.


  • 1
    P

    Wow, such a beautiful solution. Thanks a lot!


Log in to reply
 

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