You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fromfunctoolsimportcmp_to_keya= [1,4,3,2,5,7,6]
defcomp(x,y):
returnx-y# from small to largea.sort(key=lambdax: x, reverse=True)# sort from large to smalla.sort(key=cmp_to_key(comp)) # from small to largeb= [[1,2],[1,3],[2,4],[2,3],[5,7],[5,1]]
b.sort(key=lambdax: (x[0],x[1])) # sort by first index, then second
PriorityQueue
fromqueueimportPriorityQueueq=PriorityQueue()
q.put(1)
q.put(3)
whilenotq.empty():
num=q.get()
print(num) # from small to bigimportheapqq= [3, 5, 1, 2, 6, 8, 7]
heapq.heapify(q)
print(q)# [1, 2, 3, 5, 6, 8, 7]heapq.heappop(q) #1heapq.heappop(q) #2heapq.heappush(q, 4) #add 4 in heapprint(q[0]) #smallest element# with custom priorityheappush(q, (10, task1)) # 10 is the priority
Binary search tree
# pip install sortedcontainersfromsortedcontainersimportSortedListsl=SortedList([10, 11, 12, 13, 14])
# sl = SortedList(key=lambda x: -x)sl.bisect_left(12) # return 2, like C++ lower_boundsl.bisect_right(12) # return 3, like C++ upper_boundSortedList.remove(10) # value must be a member, or use discard() SortedList.add(5)