Python嵌套for循环遍历二维数组实现停车查询返回False如何解决
whereCanIPark函数问题排查与修复
原有代码的错误点
- 循环逻辑错误:外层循环直接遍历行元素而非行索引
y,内层循环错误遍历整个二维列表spots而非当前行的列索引x,无法获取正确的坐标值 - 取值逻辑错误:判断车位类型时直接拿整个二维列表
spots和字符对比,没有取对应坐标spots[y][x]的车位标识进行判断 - 逻辑运算优先级错误:
and优先级高于or,原有条件写法例如vehicle == "small" and spots == "S" or spots == "R"实际等价于(vehicle == "small" and spots == "S") or (spots == "R"),只要车位是R不管车辆类型都会命中,逻辑完全不符合要求 - 提前返回错误:在单次循环判断的else分支直接返回False,导致第一个车位不符合要求时就直接终止遍历返回结果,不会检查后续车位
修复后的代码
def whereCanIPark(spots, vehicle): # 遍历行获取行号y for y in range(len(spots)): current_row = spots[y] # 遍历列获取列号x for x in range(len(current_row)): current_spot = current_row[x] # 按停车规则判断 if vehicle == "regular" and current_spot == "R": return [x, y] elif vehicle == "small" and (current_spot == "S" or current_spot == "R"): return [x, y] elif vehicle == "motorcycle" and (current_spot == "S" or current_spot == "R" or current_spot == "M"): return [x, y] # 所有车位遍历完无符合条件的再返回False return False print(whereCanIPark( [ # 列号为X # 0 1 2 3 4 5 ['s', 's', 's', 'S', 'R', 'M'], # 0 行号为Y ['s', 'M', 's', 'S', 'r', 'M'], # 1 ['s', 'M', 's', 'S', 'r', 'm'], # 2 ['S', 'r', 's', 'm', 'r', 'M'], # 3 ['S', 'r', 's', 'm', 'r', 'M'], # 4 ['S', 'r', 'S', 'M', 'M', 'S'] # 5 ], 'regular' ))
运行结果
修复后代码输出为[4, 0],与预期一致。
内容的提问来源于stack exchange,提问作者Jeepofun
相关产品推荐
相关产品推荐

