w3resource

Python: Rotate a Deque Object specified number (positive) of times


13. Rotate a Deque a Specified Number (Positive) of Times

Write a Python program to rotate a Deque Object a specified number (positive) of times.

Sample Solution:

Python Code:

# Import the collections module to use the deque data structure
import collections

# Declare an empty deque object named 'dq_object'
dq_object = collections.deque()

# Add elements to the deque from left to right
dq_object.append(2)
dq_object.append(4)
dq_object.append(6)
dq_object.append(8)
dq_object.append(10)

# Print a message to indicate the display of the deque before rotation
print("Deque before rotation:")

# Print the content of 'dq_object'
print(dq_object)

# Rotate the deque once in the positive direction (to the right)
dq_object.rotate()

# Print a message to indicate the display of the deque after 1 positive rotation
print("\nDeque after 1 positive rotation:")

# Print the content of 'dq_object' after one rotation
print(dq_object)

# Rotate the deque twice in the positive direction (to the right)
dq_object.rotate(2)

# Print a message to indicate the display of the deque after 2 positive rotations
print("\nDeque after 2 positive rotations:")

# Print the content of 'dq_object' after two rotations
print(dq_object) 

Sample Output:

Deque before rotation:
deque([2, 4, 6, 8, 10])

Deque after 1 positive rotation:
deque([10, 2, 4, 6, 8])

Deque after 2 positive rotations:
deque([6, 8, 10, 2, 4])

Flowchart:

Flowchart - Python Collections: Rotate a Deque Object specified number (positive) of times.

For more Practice: Solve these Related Problems:

  • Write a Python program to rotate a deque by one position to the right using the rotate() method and print the result.
  • Write a Python program to implement multiple positive rotations on a deque and display the final order of elements.
  • Write a Python program to use a loop to perform positive rotations on a deque, printing the deque after each rotation.
  • Write a Python program to compare the results of a single large positive rotation versus multiple small rotations that add up to the same value.

Python Code Editor:

Previous: Write a Python program to count the number of times a specific element presents in a deque object.
Next: Write a Python program to rotate a deque Object specified number (negative) of times.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.