Collections.deque() HackerRank Solution In Python

collections.deque()

deque is a double-ended queue. It can be used to add or remove elements from both ends.

Deques support thread safe, memory efficient appends an1d pops from either side of the deque with approximately the same O(1) performance in either direction.

Click on the link to learn more about deque() methods.
Click on the link to learn more about various approaches to working with deques: Deque Recipes.

Example

Code
>>> from collections import deque>>> d = deque()>>> d.append(1)>>> print ddeque([1])>>> d.appendleft(2)>>> print ddeque([2, 1])>>> d.clear()>>> print ddeque([])>>> d.extend('1')>>> print ddeque(['1'])>>> d.extendleft('234')>>> print ddeque(['4', '3', '2', '1'])>>> d.count('1')1>>> d.pop()'1'>>> print ddeque(['4', '3', '2'])>>> d.popleft()'4'>>> print ddeque(['3', '2'])>>> d.extend('7896')>>> print ddeque(['3', '2', '7', '8', '9', '6'])>>> d.remove('2')>>> print ddeque(['3', '7', '8', '9', '6'])>>> d.reverse()>>> print ddeque(['6', '9', '8', '7', '3'])>>> d.rotate(3)>>> print ddeque(['8', '7', '3', '6', '9'])

Task

Perform appendpoppopleft and appendleft methods on an empty deque d.

Input Format

The first line contains an integer N, the number of operations.
The next N lines contains the space separated names of methods and their values.

Constraints

0 < N ≤ 100

Output Format

Print the space separated elements of deque d.

Sample Input

6append 1append 2append 3appendleft 4poppopleft

Sample Output

1 2

Solution – Collections.deque() In Python | HackerRank

from collections import dequed = deque()for _ in range(int(input())):    cmd = input().split()    if cmd[0] == "pop":        d.pop()    elif cmd[0] == "append":        d.append(cmd[1])    elif cmd[0] == "appendleft":        d.appendleft(cmd[1])    elif cmd[0] == "popleft":        d.popleft()        for i in range(len(d)):    print(d[i], end=' ')

NOTE: The problem solved above, Collections.deque(), was generated by HackerRank and the solution was brought by the admin of  CodingSolutions for educational purpose. Got any issues with the code? Ask your questions in the comment box and I shall attend to it.

Comments