Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中检查邻接关系会犯错误_Python_Algorithm - Fatal编程技术网

在Python中检查邻接关系会犯错误

在Python中检查邻接关系会犯错误,python,algorithm,Python,Algorithm,我正在处理这个leetcode问题。我得到了一个类似于flowerbed=[1,0,0,0,1]的列表和一个类似于n=1的整数。规则是,给定一个包含0和1的整数数组flowerbed,其中0表示空,1表示不空,整数n,如果n可以在花坛中种植新花而不违反无相邻花规则,则返回 示例1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Input: flowerbed = [1,0,0,0,1], n = 2 Output: false 示例2

我正在处理这个leetcode问题。我得到了一个类似于
flowerbed=[1,0,0,0,1]
的列表和一个类似于
n=1
的整数。规则是,给定一个包含
0
1
的整数数组
flowerbed
,其中
0
表示空,
1
表示不空,整数
n
,如果
n
可以在花坛中种植新花而不违反无相邻花规则,则返回

示例1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
示例2:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
这是我的密码。我正在启动一个从索引1到
len(flowerbed)-2的for循环,我正在检查当前值、我前面的值和我后面的值是否都是0,如果是,我将把
计数器
增加1。最后,通过比较
计数器
n
返回布尔值

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        counter = 0
        
        for i in range(1, len(flowerbed)-2):
            if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
                counter += 1
            
        return counter == n
然而,对于这个测试用例,它告诉我它没有签出。我不明白为什么。花坛上有两个有效的花点

Input:    [1,0,0,0,0,1]
          n = 2
Output:   true
Expected: false

您还应更新循环中的花坛列表:

if flowerbed[i] == 0 and flowerbed[i-1] == 0 and flowerbed[i+1] == 0:
    counter += 1
    flowerbed[i]=1

这样,在尝试种植新种子时,也会考虑放置种子。此外,我将考虑使用<代码>静态方法> /代码>装饰器>代码> CabPoodos.P/>