Python 1 line solution, is this valid?


  • 1
    N

    Does this break the "spirit" of the question?
    '''

    class Solution(object):

    def findMaxConsecutiveOnes(self, nums):
    
        return max(''.join(map(str,nums)).split('0')).count('1')
    

    '''


  • 2

    I don't see why it wouldn't be valid. And it's quite interesting. I previously posted one which maps to lengths before taking the max, which should be a bit faster and which I find more obvious. But yours is shorter and still has the same complexity class, Θ(|nums|).

    But you could just use the length instead of counting ones:

    def findMaxConsecutiveOnes(self, nums):
        return len(max(''.join(map(str, nums)).split('0')))
    

    Just found a hackish even shorter one based on mine, though:

    def findMaxConsecutiveOnes(self, nums):
        return max(map(len, `nums`.split('0'))) / 3

  • 0
    N

    @StefanPochmann I dont quite understand the "hackish" one you posted. what do the ' ' marks do before and after nums? I've never seen that notation before. furthermore, what does the / 3 accomplish?


  • 1

    @N413 Backticks do the same as repr (in Python 2. They were removed in Python 3). So for example for [1, 0, 1, 1, 0, 1] you get its string representation '[1, 0, 1, 1, 0, 1]'. When you split that by '0', you get the strings '[1, ' and ', 1, 1, ' and ', 1]'. Since every 1 is accompanied by a comma and a space, I need to divide the length by 3. There are some extra characters like the [ but the integer division rounding down happens to perfectly take care of this. That's the main reason I called it "hackish" :-)


  • 0
    N

    ah, thank you, def a bit hacky but it works! nice.


  • 0
    P

    How about this one:
    sorted(map(len,(''.join(map(str,text)).split("0"))),reverse=True)[0]


Log in to reply
 

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