[LeetCode] 605. Can Place Flowers

Semidragon·2023년 8월 8일
0

CodingTest

목록 보기
4/80

1. Question

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true

2. Thoughts

3. Tips learned

3.1 iter() and enumerate()

we can use the iterater like:

list = ["a", "b", "c", "d", "e"]
it = iter(enumerate(list))
for i, val in it:
	print(i,val)

This will produce:

0 a
1 b
2 c
3 d
4 e

enumerate()

enumerate() is a built-in Python function that returns an iterator, which produces pairs containing the index and the value from the iterable. In simpler terms, it allows you to loop over a collection and have an automatic counter.

Typical usage:

for index, value in enumerate(some_list):
    print(index, value)

Without enumerate(), if you wanted to track the index of the current item, you'd probably use a pattern like this:

index = 0
for value in some_list:
    print(index, value)
    index += 1

But enumerate() provides a cleaner and more Pythonic way to achieve this.

iter()

iter() is a built-in Python function that returns an iterator object for the provided iterable. An iterator is an object that can be iterated (looped) over. It's designed to return its members one at a time.

Once you have an iterator object, you can use the next() function to manually get the next item from it:

my_list = [1, 2, 3]
it = iter(my_list)
print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

When there are no more items to return, the iterator raises a StopIteration exception, which signals the end of the loop in constructs like the for loop.

Combining enumerate() and iter()

In your code:

list = ["a", "b", "c", "d", "e"]
it = iter(enumerate(list))
for i, val in it:
	print(i, val)

enumerate(list) returns an iterator that yields pairs of (index, value). When you pass this to iter(), you're essentially getting another iterator (though it's a bit redundant since enumerate() already returns an iterator).

The for loop then unpacks these pairs into i and val on each iteration.

In practice, you don't usually need to use iter() directly when working with for loops in Python, because the for loop will implicitly call iter() on the iterable you provide. But understanding iter() can be useful for more advanced use cases or for when you want to manually control the iteration process.

4. My solution

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        possible = 0
        it = iter(enumerate(flowerbed))

        for i, flower in it:
            # If empty
            if flowerbed[i] == 0:
                # And next also 0
                if i == len(flowerbed) - 1 or flowerbed[i + 1] == 0:
                    possible = possible + 1
                else:
                    next(it,None)
            next(it, None)
        return possible >= n

5. AI Solution and Improvements

Improvements:

Instead of using iterators, you can use a simple while loop for better clarity.

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        possible = 0
        i =0

        while i < len(flowerbed):
        # If empty
            if flowerbed[i] == 0:
                # And next also 0
                if i == len(flowerbed) - 1 or flowerbed[i + 1] == 0:
                    possible = possible + 1
                else:
                    i+=1
            i+=2

        return possible >= n
profile
Semidragon's network [CS undergrad @ Sungkyunkwan University | Networks + System @ CSI]

1개의 댓글

comment-user-thumbnail
2024년 2월 21일

I don't understand question 605 at all, maybe I'm too dumb for it. I bet not even Luis Flores could figure it out. This is without doubt a very difficult question.

답글 달기