40.python堆、集合、双端队列
python堆、集合、双端队列
# This is a sample Python script. # 1# 1 # 2# 2 # Press Shift+F10 to execute it or replace it with your code.# 3# 3 # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.# 4# 4 # 5# 5 # 6# 6 def print_hi(name): # 7# 7 # Use a breakpoint in the code line below to debug your script.# 8# 8 print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.# 9# 9 #10#10 #11#11 # Press the green button in the gutter to run the script.#12#12 if __name__ == '__main__': #13#13 #print_hi('PyCharm') #14#14 import fileinput #15#15 #for line in fileinput.input(inplace=True): #16#16 line = fileinput.input(inplace=True) # line = line.rstrip() # 17#17 num = fileinput.lineno() # 18#18 # print('{:<50}#{:2d}'.format(line, num)) # 19#19 #print('#{:2d}'.format(num)) #python list的使用 alist = ['aa', 'bb', 'cc'] alist.append('dd') print('list操作:',alist) # print_hi('PyCharm') # list的使用 zlist = ['hello', 'quant', 'vvp', 'vvp3a'] z2 = zlist[1:] # 从索引1开始提取信息 # 从索引1开始提取信息 z2 = zlist[0:] # 从索引0开始提取信息 print(z2) print(zlist) print(zlist[2:4]) # []前开后闭,包前不包后 char_list = 'abc' print('char1:', char_list[0]) print('char1:', char_list[1]) #集合,集合中元素的排列顺序不确定 aa_set=set(range(10)) print('set:', aa_set) #堆 heapq from heapq import * from random import shuffle data = list(range(10)) shuffle(data) heap2= [] for n in data: heappush(heap2, n) print('堆heap2:', heap2) heappush(heap2, 0.8) print('堆heap2 压入:', heap2) pop1 = heappop(heap2) print('堆heap2 弹出:', pop1) print('堆heap2 弹出1:', heap2) pop2 = heappop(heap2) print('堆heap2 弹出:', pop2) print('堆heap2 弹出2:', heap2) #它从堆中弹出最小的元素,再压入一个新元素 heapreplace(heap2, 77) print('堆heapreplace:', heap2) print(nlargest(1, heap2)) #返回堆中最大的元素 print(nsmallest(1, heap2))#返回堆中最小的元素 #双端队列(及其他集合)在需要按添加元素的顺序进行删除时,双端队列很有用 from collections import deque q = deque(range(6)) q.append(7) print('增加:',q) print('pop一次:',q.pop()) print('popleft,',q.popleft()) print(q) q.rotate(3) print('after rotate 顺序移动3次:',q) q.rotate(-1) print('after rotate -1逆序移动1次', q)
欢迎讨论,相互学习。
cdtxw@foxmail.com