File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
docs/19_python内置常用算法和数据结构 Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change 23
23
| 堆算法 | | heapq模块 |
24
24
| 优先级队列 | | queue.PriorityQueue |
25
25
| 缓存算法 | | functools.lru_cache(Least Recent Used, python3) |
26
+
27
+ # 一些坑
28
+
29
+ 如果你经常使用 python2 or python3 刷题(比如力扣leetcode),有一些坑或者技巧需要注意:
30
+
31
+ - python3 和 python2 的 dict 有所用不同,python3.7 之后的 dict 会保持插入顺序, python2 不要依赖 dict 迭代顺序,请使用 OrderedDict
32
+ - 正确初始化一个二维数组:` dp = [[0 for _ in range(col)] for _ in range(row)] ` ,不要用 ` dp = [[0] * n] * m ` , 否则里边都
33
+ 引用的同一个 list,修改一个都会变
34
+ - python在数值范围建议用:` MAXINT = 2**63-1; MININT = -2**63 ` 。因为 python2 sys.maxint 和 python3 sys.maxsize 不统一
35
+
36
+
37
+ # 链表题目调试函数
38
+
39
+ ``` py
40
+ # 编写链表题目经常用到的一些通用函数和调试函数,定义等,方便代码调试
41
+
42
+ class ListNode (object ):
43
+ def __init__ (self , val = 0 , next = None ):
44
+ self .val = val
45
+ self .next = next
46
+
47
+ def __str__ (self ):
48
+ return ' Node({} )' .format(self .val)
49
+
50
+ # 用来输出调试
51
+ __repr__ = __str__
52
+
53
+
54
+ # 缩写,单测方便写,比如构建链表 1->2->3 N(1, N(2, N(3)))
55
+ N = Node = ListNode
56
+
57
+
58
+ def to_list (head ):
59
+ """ linked list to python []"""
60
+ res = []
61
+ curnode = head
62
+ while curnode:
63
+ res.append(curnode.val)
64
+ curnode = curnode.next
65
+ return res
66
+
67
+
68
+ def gen_list (nums ):
69
+ """ 用数组生成一个链表方便测试 [1,2,3] 1->2->3
70
+ """
71
+ if not nums:
72
+ return None
73
+ head = ListNode(nums[0 ])
74
+ pre = head
75
+ for i in range (1 , len (nums)):
76
+ node = ListNode(nums[i])
77
+ pre.next = node
78
+ pre = node
79
+ return head
80
+
81
+
82
+ def print_list (head ):
83
+ """ 打印链表"""
84
+ cur = head
85
+ res = " "
86
+ while cur:
87
+ res += " {} ->" .format(cur.val)
88
+ cur = cur.next
89
+ res += " nil"
90
+ print (res)
91
+ ```
You can’t perform that action at this time.
0 commit comments