본문 바로가기
코딩 공부

Leetcode: Can Place Flowers python 풀이

by 카우보이연구소 2022. 1. 23.

요즘에는 개발자들이 회사에 취업하기 위해서 사용한다는 리트코드 (leetcode) 사이트의 문제들을 풀어보고 있습니다. 이제 막 시작한 초보자라 힘든 점이 많아서 이렇게 글로 남겨서 복습하려고 합니다.


문제: Can Place Flowers
등급: Easy

분명히 Easy인데.. easy인데... easy란 말야 ㅠㅠ

내용:

0과 1의 array가 주어지고, 꽃을 심을 곳을 찾아야 한다. 꽃은 0에만 심을 수 있고, 옆에도 0이야 한다. 또한, 꽃의 개수도 주어지는데, 이 꽃의 개수(n)가 실제 심을 수 있는 값이랑 같다면 True를 반환, 틀리다면 False를 반환하게 돼있다.

꽃은 아름답지만 심기는 어려웠다.

<코드>

처음에 든 생각으로는, 000, 이렇게 '0이 세 개가 주어지면 꽃을 심을 수 있겠다'이었다. 그래서, 000이 되면 count +=1 하게 코드를 적었다.

 

그랬더니, 계속 에러가 떴다. 처음 '001'일 경우를 카운트 안 했기 때문이다.

 

그래서, 처음과 마지막 '00'의 케이스에 대한 count를 하게 적었다. 확실하게 깔끔하게 적는 재주는 없다:

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        count = 0
        i = 0
        
        if len(flowerbed) == 1:
            if not flowerbed[i]:
                count += 1
                return count == n
            else:
                return count == n
        if not i and not flowerbed[1] and not flowerbed[i]:
            i += 2
            count += 1
            
        while i < (len(flowerbed)-2):
            if flowerbed[i]:
                i += 1
                continue
            else:
                if not flowerbed[i+1] and not flowerbed[i+2]:
                    i += 2
                    count += 1
                    continue
                i += 1
        
        if i == (len(flowerbed) -2) and not flowerbed[i] and not flowerbed[i+1]:
            count += 1
        
        return count == n

그런데, 문제는 통과가 안된다는 점!

왜....?

분명 앞이랑 뒤에 하나씩 꽃을 심을 수 있는 것 아닌가....?

 

일단 discussion으로 향했다.

 

너무나도 똑똑한 한 줄을 보았다.

flowerbed = [0] + flowerbed + [0]  

내가 기껏 길게 적었던 첫 if와 마지막 if를 깔끔하게 지울 수 있는 한 방이었다.

 

아, 그리고 위에 헷갈렸던 점은 나의 불찰... 꽃의 개수를 줬으니 그보다 많이 심을 수 있어도 True였던 것이다. (위의 내용은 약간 틀리다는 점)

 

정말 힘들게 몇 번의 wrong answer를 통해 나온 코드는 이거가 되겠다.

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        count = 0
        i = 0
        
        if len(flowerbed) == 1 or len(flowerbed) == 2:
            if not flowerbed[i]:
                count += 1
                return count >= n
            else:
                return count >= n
        if not i and not flowerbed[1] and not flowerbed[i]:
            i += 1
            count += 1
            
        while i < (len(flowerbed)-2):
            if flowerbed[i]:
                i += 1
                continue
            else:
                if not flowerbed[i+1] and not flowerbed[i+2]:
                    i += 2
                    count += 1
                    continue
                i += 1
        
        if i == len(flowerbed)-2 and not flowerbed[len(flowerbed) -2] and not flowerbed[len(flowerbed) -1]:
            count += 1
        
        return count >= n

아이 더러워

 

눈의 정화를 위해서 훨씬 깔끔한 코드들을 보도록 하자:

class Solution(object):
    def canPlaceFlowers(self, flowerbed, n):
        i , count = 0, 0
        
        while (i < len(flowerbed)):
            if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and (i == (len(flowerbed) - 1) or flowerbed[i+1] == 0):
                flowerbed[i] = 1
                count += 1
            i += 1
                    
        return count >= n

 

다른 멋진 솔루션들도 많은데.... 힘들어서 더는 못하겠다!

 

<오류, 힘들었던 점>

너무 힘들었다. 왠지 모르게 안 되는 경우가 너무 많다...

 

<총평>

 

오늘만큼은 UnHappy coding!

 

Can Place Flowers - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

 

 

댓글