力扣:第k个数
class Solution:
def getKthMagicNumber(self, k: int) -> int:
factors = [3, 5, 7]
seen = {1}
heap = [1]
for i in range(k - 1):
curr = heapq.heappop(heap)
for factor in factors:
if (nxt := curr * factor) not in seen:
seen.add(nxt)
heapq.heappush(heap, nxt)
return heapq.heappop(heap)
其中nxt := curr * factor
中的:=
符号是什么含义呀?
:=
是python3.8
的新特性,称为海象运算符。它将值赋给变量,整体又作为表达式的一部分,使得赋值和判断合并,代码更加简洁。
上述代码等价于,
class Solution:
def getKthMagicNumber(self, k: int) -> int:
factors = [3, 5, 7]
seen = {1}
heap = [1]
for i in range(k - 1):
curr = heapq.heappop(heap)
for factor in factors:
nxt = curr * factor
if nxt not in seen:
seen.add(nxt)
heapq.heappush(heap, nxt)
return heapq.heappop(heap)
关于符号:=
,python
官方教程为:https://docs.python.org/3/whatsnew/3.8.html。