w3resource

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

Python Collections: Exercise-13 with Solution

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

Sample Solution:

Python Code:

import collections
# declare an empty deque object
dq_object = collections.deque()
# Add elements to the deque - left to right
dq_object.append(2)
dq_object.append(4)
dq_object.append(6)
dq_object.append(8)
dq_object.append(10)
print("Deque before rotation:")
print(dq_object)
# Rotate once in positive direction
dq_object.rotate()
print("\nDeque after 1 positive rotation:")
print(dq_object)
# Rotate twice in positive direction
dq_object.rotate(2)
print("\nDeque after 2 positive 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:

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

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz


Python: Tips of the Day

Capitalizes the first letter of a string:

Example:

def tips_capitalize(s, lower_rest=False):
  return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])
print(tips_capitalize('pythonTips'))
print(tips_capitalize('pythonTips', True))

Output:

PythonTips
Pythontips