题:从格子顶部n列放球,返回球的落点。如果停在中间,在为-1。
解:模拟(见官方题解)
如果下落的下一步掉到边缘(<0 or >=n),或下一个挡板方向(row[col] != dir))则听在中间。
class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: #grid[i][j] = 1:右 ; =-1 :左 m,n = len(grid),len(grid[0]) res = [-1]*n for ball in range(n): col = ball for row in grid: dir = row[col] col += dir if col < 0 or col ==n or row[col] != dir: break else: res[ball] = col return res
for~else语法:4. 其他流程控制工具 — Python 3.10.2 文档
else可以和for或while循环搭配。for 循环中,可迭代对象中的元素全部循环完毕,或 while 循环的条件为假时,执行该子句;break 语句终止循环时,不执行该子句。
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
输出:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
个人理解:
else和循环搭配可以认为循环正常结束没被打断(break)则做else。我们可以利用这个特点替代if 循环结束
if 循环结束: do()
为
else: do()
arr = [1, 2, 3, 4, 5] n = len(arr) i = 0 while i < n: if arr[i] > 7: print('find x>7,x=', arr[i]) break i += 1 ####if 循环结束: if i == n: print("can't find x>7")
arr = [1, 2, 3, 4, 5] n = len(arr) i = 0 while i < n: if arr[i] > 7: print('find x>7,x=', arr[i]) break i += 1 #else替代"if 循环结束" else: print("can't find x>7")