w3resource

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

Python Collections: Exercise-14 with Solution

Write a Python program to rotate a Deque Object specified number (negative) 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 negative direction
dq_object.rotate(-1)
print("\nDeque after 1 negative rotation:")
print(dq_object)
# Rotate twice in negative direction
dq_object.rotate(-2)
print("\nDeque after 2 negative rotations:")
print(dq_object)

Sample Output:

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

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

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

Flowchart:

Python Collections: Rotate a deque Object specified number (negative) 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 rotate a Deque Object specified number (positive) of times.
Next: Write a Python program to find the most common element of a given list.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value:

Example:

def tips_map_values(obj, fn):
  ret = {}
  for key in obj.keys():
    ret[key] = fn(obj[key])
  return ret
users = {
  'Owen': { 'user': 'Owen', 'age': 29 },
  'Eddie': { 'user': 'Eddie', 'age': 15 }
}

print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}

Output:

{'Owen': 29, 'Eddie': 15}