Python Basics

Python Basics

Math

在正数时,int(a / b)a // b 通常结果相同,但在负数时可能不同:

  • int(a / b) 是向零取整(trunc)。如果你希望总是向零取整,使用 int(a / b)
  • // 是向下取整(floor)。如果你希望总是向下取整,使用 a // b

另外,取模运算 a % b也遵从 floor法则,a = (a // b) * b + (a % b) -> a % b = a - (a // b) * b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 向零取整
print(int(3 / 2))  # 1
print(int(-3 / 2))  # -1

# 向下取整
print(int(3 // 2))  # 1
print(int(-3 // 2))  # -2
# floor(-1.5) = -2

# 取模
print(10 % 3)  # 1
print(-10 % 3)  # 2
# -10 - (-10//3) * 3 = -10 - (-4) * 3 = 2

Arrays

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
# Sublists (aka slicing), 左闭右开
arr = [1, 2, 3, 4]
print(arr[1:3])  # [2, 3]
# Similar to for-loop ranges, last index is non-inclusive

# But no out of bounds error
print(arr[0:10])  # [1, 2, 3, 4]

# Reverse
nums = [1, 2, 3]
nums.reverse()
print(nums)  # [3, 2, 1]

# Sorting (in-place, ascending)
arr = [5, 4, 7, 3, 8]
arr.sort()
print(arr)  # [3, 4, 5, 7, 8]

arr.sort(reverse=True)
print(arr)  # [8, 7, 5, 4, 3]

# Custom sort (e.g., by length of string)
arr = ["bob", "alice", "jane", "doe"]
arr.sort(key=lambda x: len(x))
print(arr)  # ['bob', 'doe', 'jane', 'alice']

# 2-D lists
arr = [[0] * 4 for i in range(4)]
print(arr)
print(arr[0][0], arr[3][3])

# This won't work
# arr = [[0] * 4] * 4

python里面的区间基本上是左闭右开,比如range、slicing

Strings

1
2
3
4
5
6
7
8
9
# Valid numeric strings can be converted
print(int("123") + int("123"))  # 246

# And numbers can be converted to strings
print(str(123) + str(123))  # 123123

# In rare cases you may need the ASCII value of a char
print(ord("a"))  # 97
print(ord("b"))  # 98

Queues

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Queues (double ended queue)
from collections import deque

queue = deque()
queue.append(1)
queue.append(2)
print(queue)  # deque([1, 2])

queue.popleft()
print(queue)  # deque([2])

queue.appendleft(1)
print(queue)  # deque([1, 2])

queue.pop()
print(queue)  # deque([1])

Heaps

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
34
35
36
37
38
39
40
41
42
43
44
import heapq

# under the hood are arrays
minHeap = []
heapq.heappush(minHeap, 3)
heapq.heappush(minHeap, 2)
heapq.heappush(minHeap, 4)

# Min is always at index 0
print(minHeap[0])  # 2

while len(minHeap):
    print(heapq.heappop(minHeap))
# 2
# 3
# 4

# No max heaps by default, work around is
# to use min heap and multiply by -1 when push & pop.
maxHeap = []
heapq.heappush(maxHeap, -3)
heapq.heappush(maxHeap, -2)
heapq.heappush(maxHeap, -4)

# Max is always at index 0
print(-1 * maxHeap[0])  # 4

while len(maxHeap):
    print(-1 * heapq.heappop(maxHeap))
# 4
# 3
# 2

# Build heap from initial values
arr = [2, 1, 8, 4, 5]
heapq.heapify(arr)
while arr:
    print(heapq.heappop(arr))
# 1
# 2
# 4
# 5
# 8

References

This post is licensed under CC BY 4.0 by the author.