coding/python常用语法.md

138 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 技巧分类:
- 两指针
- 滑动窗口
- 二分法
- 字符串
- 数组
- 哈希表
- 链表
-
- 单调栈
-
- 排序
- 随机
- 累加和
- 二进制
- 贪心算法
-
- 回溯
- 图Visited
- 动态规划
## python语法
```python
# 列表
range(0, 111, 2) ; range(111, -1, -1)
for i, num in enumerate(nums):
nums.index(30) nums.index(30, 2, 5) # 在索引 2 到 5 的范围内查找值 30 的索引
max_value = max(nums)
max_index = nums.index(max_value)
sorted(nums) nums.sort()
nums.reverse()
res = [float('inf')] * 6
[[0] * n for _ in range(m)]
result.append(path[:])
```
```python
# 栈
stack = []
stack.append(s)
stack.pop()
```
```python
# 字符串
for c in t: # t is str; c is char
for c1, c2 in zip(s, t): # s, t are str
for i, ch in enumerate(s): # s: str
ord(i) - ord("a")
chr(66) #将 Unicode 编码值(整数)转换为对应的字符
str(3)
int("3")
s[0:6] # s is str 的切片语法
repeated_s = s * 3
s.upper() #不会改变原字符串,如果想要修改,需要重新赋值
s = "hello" res=list(s) ''.join(res)
s = s1 + " " + s2
```
```python
# 字典
count = {}; count[s] = count.get(s, 0) + 1 del count[s]
count = collections.Counter(s1)
dic = {}
count_dict = defaultdict(int) # 使用 int默认值为 0
list_dict = defaultdict(list) # 使用 list默认值为空列表
set_dict = defaultdict(set) # 使用 set默认值为空集合
if s in dic: # s is key
dic["age"] = 26
del dic["city"]
for key in dic:
for value in dic.values():
for key, value in dic.items():
dict(sorted(my_dict.items(), key=lambda item: item[0]))
```
```python
# 队列
from collections import deque
d=deque([1, 2, 3, 4, 5])
d.append(3) d.appendleft(0)
d.pop() d.popleft()
d[0] d[-1] # 查看左,右端元素
```
```python
# 堆
import heapq
heap = [1, 5, 10]
heapq.heapify(heap)
heapq.heappush(heap, 1)
heapq.heappop(heap)
heapq.heappush(pri_que, (freq, key)) #小顶堆大小序按照元组第一个元素freq
```
```python
# 集合
set = {1, 2, 3, 4}
set = set([1, 2, 3, 4])
set = set("aeiouAEIOU")
set.add(3)
set.update([1, 5])
set.remove(2)
set.pop() 随机删除一个元素
set1.union(set2)
if 3 in set:
```
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
```python
import bisect
bisect.bisect_right(nums, x)
n, r = divmod(n, 10)
a % b a // b
lambda x, y: int(x / y)
from operator import add, sub, mul
random.randint(1, 6)
1 << 3 # 将数字 1 左移 3 位 = 8
# 异或操作符 ^ 的规则是:相同为 0相异为 1
x & (x - 1) # 消去x最后一位的1
x & (~ (x - 1)) # 获得最右边1开始至结尾
```