Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- A deque (double-ended queue) is a data structure that allows insertion and removal of elements from both ends (front and back). This flexibility makes it useful for scenarios requiring efficient additions and deletions from both ends, such as:
- - Implementing LRU (Least Recently Used) caches: Quickly remove the least recently used item from one end and add new items to the other.
- - Handling sequences of items: Suitable for scenarios like undo functionality in applications, where you might need to add actions to the front or back of a list.
- - Breadth-first search (BFS) in graph algorithms: Efficiently enqueue and dequeue nodes.
- Deques provide O(1) time complexity for operations at both ends, making them more efficient than lists when such operations are needed frequently.
- """
- from collections import deque
- # Creating a deque
- my_deque = deque([1, 2, 3, 4, 5])
- # Creating an empty deque
- empty_deque = deque()
- # Adding elements to the deque
- my_deque.append(6) # Add an element to the right end
- my_deque.appendleft(0) # Add an element to the left end
- # Removing elements from the deque
- right_element = my_deque.pop() # Remove and return an element from the right end
- left_element = my_deque.popleft() # Remove and return an element from the left end
- # Accessing elements in the deque
- first_element = my_deque[0] # Access the first element
- last_element = my_deque[-1] # Access the last element
- # Modifying elements in the deque
- my_deque[1] = 10 # Modify the second element
- # Checking for elements
- is_in_deque = 10 in my_deque # Check if an element is in the deque
- is_not_in_deque = 100 not in my_deque # Check if an element is not in the deque
- # Getting the length of the deque
- length = len(my_deque) # Get the number of elements in the deque
- # Iterating through the deque
- for element in my_deque:
- print(element) # Print each element in the deque
- # Reversing the deque
- my_deque.reverse() # Reverse the elements in the deque in place
- # Extending the deque
- my_deque.extend([7, 8, 9]) # Add multiple elements to the right end
- my_deque.extendleft([-1, -2, -3]) # Add multiple elements to the left end (added in reverse order)
- # Rotating the deque
- my_deque.rotate(1) # Rotate the deque one step to the right
- my_deque.rotate(-2) # Rotate the deque two steps to the left
- # Clearing the deque
- my_deque.clear() # Remove all elements from the deque
- # Copying the deque
- copied_deque = my_deque.copy() # Create a shallow copy of the deque
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement