Chapter 1c: Python as a Computer Language

triangle-exclamation

1. Built-in Collections (Python)

# List
array = [ None ] * n

# alternative to array map 
array = [ x*2 for x in range(i, j) ]  

# 2D Array, dont use [[0]*cols] * rows as 
# it will use the same object for all subarrays  
_2d_array = [ [0]*cols for x in range(rows) ] 
flattened = [ ele for subarr in _2d_array for ele in subarr]

# Use List as a stack
array.append(x)
curr = array.pop()

# Use List as a queue
queue = deque(array)
queue.append(x)
curr = queue.popleft()

# Use List as heap
heap = heapq.heapify(array)
heapq.heappush(heap, x)
curr = heapq.heappop(heap)

2. Mutate String

circle-exclamation

3. Iterators and Iterable

Reference: https://opensource.com/article/18/3/loop-better-deeper-look-iteration-pythonarrow-up-right

circle-exclamation

4. Decimal Precision Limitation

Python中的小数都不是完全精确的,根本原因是因为用二进制来表示小数的limitation: https://docs.python.org/3/tutorial/floatingpoint.htmlarrow-up-right

5. Inline Function

circle-info

需要把问题的一些子功能拆分出来时,可以用inline function来定义,这样免去了需要母函数需要传递很多参数给子函数的麻烦,使得code的逻辑更清晰。注意如果我们需要在inline function的scope内更改这些变量的话,要用nonlocal关键词,类似于C++中的pass-by-reference。

Inline function普遍使用于递归,因为递归函数的输入输出,经常和问题需要的输入输出不同。

6. Instance variable

circle-info

Python不存在private的instance variable(从convention来说可以在他们的命名前加上__ ),但是可以用@property@setter去 override 读取和写入变量的behavior,这样保证了一件事情只有一种做法。instance variable可以在instance method中初始化,而并不一定要用__init__。

Last updated