Python - LeetCode使用到的好用Fun.

1. List Init

1.var = [x for x in x]:快速定義List的使用方式,可以搭配if來使用
2.range(start:end):產生range的int
3.len() : 長度

1
2
checkMap = [[0 for y in range(nYCount)] for x in range(nXCount)]
nLength = len(checkMap)

基本LeetCode


2. Object Init

1
2
3
4
5
6
7
8
9
10
11
12
13
#1.list() : LIST         []
#2.set() : 獨立不重覆 {}
#3.dict() : 字典 {{}}
#4.tuple() : 不可改變 ()

listVar = list([5,3,3])
setVar = set([5,3,3])

print(listVar)
print(setVar)

#[5, 3, 3]
#{3, 5}

基本LeetCode 771 807 595 804 491 832 728


3. String

1.count : 計算內容物的次數

1
2
3
4
5
6
7
class Solution:
def judgeCircle(self, moves):
return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
"""
:type moves: str
:rtype: bool
"""

基本LeetCode 657


4. List[int]

1.index : 找到對應的index
2.max : 取出最大值

1
return (A.index(max(A)))

基本LeetCode 852


5. binary Tree

binary Tree的使用範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def mergeTrees(self, t1, t2):
NewNode = TreeNode(0)
def nextLoop(tCurrent,tcopy):
if tcopy == None:
return
tCurrent.val += tcopy.val
print(tcopy.val)
if tcopy.left is not None:
if tCurrent.left == None:
tCurrent.left = TreeNode(0)
nextLoop(tCurrent.left,tcopy.left)
if tcopy.right is not None:
if tCurrent.right == None:
tCurrent.right = TreeNode(0)
nextLoop(tCurrent.right,tcopy.right)
nextLoop(NewNode,t1)
nextLoop(NewNode,t2)
if t1 == None and t2 == None:
NewNode = None
return NewNode
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""

基本LeetCode 617