Leetcode Python Summary

未来可见的一段时期要switch 到 Python了。 这里主要记录一下用Python 刷题的总结,特别是一些不知道的module, funtions等等,还有就是知道了但没有熟练应用。

对于while, if 等,None, 0 等都视作False,不用再去显示比较了。

1
2
3
4
5
6
divmod(x, y)
"""
returns a pair of numbers consisting of their quotient and remainder.
"""
x and y : x is numerator and y is denominator
x and y must be non complex

L1480: 这题学到个新的function accumulate 依次叠加

1
2
3
4
from itertools import accumulate
itr = accumulate([1,2,3,4,5])
list(itr)
## [1, 3, 6, 10, 15]

L617: 如果是BFS, 则要使用queue:

1
2
3
4
5
6
## init
queue = collections.deque([])
## same as len(queue)
## canonical way for all collections (tuples, strings, lists, dicts and all their many subtypes) to check empty or not
while queue:
pass

L1512: collecions.Counter()

1
2
3
## return a dict subclass object
## {object: count, ...}
collections.Counter("sbadbfasdbfab")

LC236: 注意这里的这里表达方式

1
2
3
4
5
6
7
def lowestCommonAncestor(self, root, p, q):
## 这个表达很省事
if root in (None, p, q): return root
## generator
left, right = (self.lowestCommonAncestor(kid, p, q)
for kid in (root.left, root.right))
return root if left and right else left or right
0%