以下是我用python刷算法的記錄,記下來以便複習
1. 線性表
- 順序表
# 創建順序表
a = []
a = list()
# 在尾部插入元素x
a.append(x)
# 刪除索引i的元素
a.pop(i)
- 鏈表
class linkNode():
def __init__(x, y)
self.val = x
self.next = y
- 堆棧
# 創建堆棧
s = []
# 壓入元素
s.append(x)
# 彈出元素
s.pop()
# 判斷是否爲空
s
# 判斷是否已滿
len(s) < maxsize
- 先進先出隊列
from queue import Queue
# 創建隊列
q = Queue(100)
# 元素x入隊
q.put(x)
# 隊首元素出隊
q.get()
# 判斷隊空,隊空返回True
q.empty()
# 判斷隊滿,隊滿返回True
q.full()
# 返回隊列大小
q.qsize()
- 優先級隊列
from queue import PriorityQueue
"""
PriorityQueue繼承了Queue,改寫了_put和_get方法,底層調用了heappush和heappop實現了優先級的管理
"""
# 創建隊列
q = PriorityQueue(100)
# 元素x入隊
q.put(x)
# 隊首元素出隊
q.get()
# 判斷隊空,隊空返回True
q.empty()
# 判斷隊滿,隊滿返回True
q.full()
# 返回隊列大小
q.qsize()
- 元組(不可變列表)
a = ()
a = tuple()
2. 字典(哈希表)
# 創建字典
a = dict()
a = {}
# 插入元素,k表示鍵,v表示值
a[k] = v
# 取出元素
a[k]
a.get(k, default)
# 查看所有鍵
a.keys()
# 查看所有值
a.values()
# 查看所有鍵值對
a.items()
3. 集合
# 創建集合
a = set()
# 添加元素x
a.add(x)
# 刪除元素x
a.remove(x)
# 集合a,b的交集
a & b
# 集合a,b的並集
a | b
4. 堆
import heapq
"""
heapq實現的是最小堆,將數組調整成堆的結構
"""
s = [3,1,4,2,6]
# 小根堆
# 將數組調整爲小根堆
heapq.heapify(s) #=> s = [1, 2, 4, 3, 6]
# 彈出最小元素
heapq.heappop(s) #=> 1
# 插入元素0
heapq.heappush(s, 0) #=> s = [0, 2, 4, 6, 3]
# 彈出最小元素並插入1
heapq.heapreplace(s, 1) #=> s = [1, 2, 4, 6, 3]
# 大根堆
ns = [(-i, i) for i in s]
heapq.heapify(ns)
heapq.heappop(ns)[1] #=> 6
5. 排序
"""
sort是可變對象(字典、列表)的方法,在原地對序列進行排序,無返回值;
sorted是python的內置函數,需要傳遞排序對象作爲參數,返回一個排序後的迭代器(不改變原數組);
"""
# sorted方法
# 對字典進行排序
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
# 對字典按照值降序排列
sorted(dic.items(), key=lambda x: x[-1], reverse=True)
# [('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
# 對字典按照鍵升序排列
sorted(dic.items(), key=lambda x: x[0], reverse=False)
[('a', 31), ('aa', 74), ('asd', 4), ('bc', 5), ('c', 3), ('d', 0)]
# sort
a = [3,4,2,1]
a.sort()