Can you help me to improve my Python code


  • 0
    T

    Hello,
    My idea is to count the number of 0s between 1s
    To deal with 0 starts or 0 ends case, I add [1 0] to the beginning if 0 starts and add [0 1] to the end.
    I think the idea is pretty simple, but I cannot write a clear and short code.
    Can you help me to improve my code?
    thanks:)

    class Solution(object):
        def canPlaceFlowers(self, flowerbed, n):
            """
            :type flowerbed: List[int]
            :type n: int
            :rtype: bool
            """
            cnt = start = end = 0
            if flowerbed[0] == 0:
                flowerbed.insert(0,0)
                flowerbed.insert(0,1)
            if flowerbed[-1] == 0:
                flowerbed.append(0)
                flowerbed.append(1)
            print(flowerbed)
            while True:
                while start < len(flowerbed) and flowerbed[start] == 1:
                    start += 1
                end = start 
                while end < len(flowerbed) and flowerbed[end] != 1:
                    end += 1
                if end > start:
                    cnt += (end - start - 1)//2
                if end >= len(flowerbed)-1:
                    return cnt >= n
                print(cnt)
                start = end
    

Log in to reply
 

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