Python使用Deque

Deque (Doubly Ended Queue) in Python is implemented using the module “collections”. Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.

Various Operations on deque:

  • append(): This function is used to insert the value in its argument to the right end of deque

  • appendleft(): This function is used to insert the value in its argument to the left end of deque

  • pop(): This function is used to delete an argument from the right end of deque

  • popleft(): This function is used to delete an argument from the left end of deque.

  • index(ele, beg, end): This function returns the first index of the value mentioned in arguments, starting searching from beg till end index.

  • insert(i, a): This function inserts the value mentioned in arguments(a) at index(i) specified in arguments.

  • remove(): This function removes the first occurrence of value mentioned in arguments.

  • count(): This function counts the number of occurrences of value mentioned in arguments.

  • extend(iterable): This function is used to add multiple values at the right end of deque. The argument passed is an iterable.

de = collections.deque([1,2,3])
de.extend([4,5,6]) # ([1,2,3,4,5,6])
  • extendleft(iterable): This function is used to add multiple values at the left end of deque. The argument passed is an iterable. Order is reversed as a result of left appends.
de = collections.deque([1,2,3])
de.extendleft([7,8,9])  # ([9,8,7,1,2,3])
  • rotate(): This function rotates the deque by the number specified in arguments. If the number specified is negative, rotation occurs to left. Else rotation is to right.
de = collections.deque([1,2,3,4])

# 负数:向左移动
# 正数:向右移动
de.rotate(-1)  # ([2,3,4,1]) 
de.rotate(-2)  # ([3,4,1,2])
de.rotate(1)   # ([4,1,2,3])
de.rotate(2)   # ([3,4,1,2])
  • reverse(): This function is used to reverse order of deque elements.
de = collections.deque([1,2,3,4])

de.reverse()  # ([4,3,2,1])

可以用deque()来做 level traversal bst

你可能感兴趣的:(Python3,python,开发语言,后端)