# Check if Queue Elements are pairwise consecutive in Python

PythonServer Side ProgrammingProgramming

Suppose we have a queue full of numbers. We have to check whether the consecutive elements in the queue are pairwise consecutive or not.

So, if the input is like que = [3,4,6,7,8,9], then the output will be True.

To solve this, we will follow these steps −

• q := define a queue and insert all elements from given list into q
• temp := a new list
• while q is not empty, do
• insert front element of queue into temp and delete front element from queue
• temp2 := a new list
• while temp is not empty, do
• insert last element of temp into temp2
• delete last element from temp
• result := True
• while size of temp2 > 1, do
• x := last element of temp2
• delete last element from temp2
• y := last element of temp2
• delete last element from temp2
• if |x - y| is not 1, then
• result := False
• insert x and y into q
• if size of temp2 is 1, then
• insert last element of temp2 into q
• return result

## Example

Let us see the following implementation to get better understanding −

import queue
def solve(que):
q = queue.Queue()
for i in que:
q.put(i)
temp = []
while q.qsize() != 0:
temp.append(q.queue)
q.get()
temp2 = []
while len(temp) != 0:
temp2.append(temp[len(temp) - 1])
temp.pop()
result = bool(True)
while len(temp2) > 1:
x = temp2[len(temp2) - 1]
temp2.pop()
y = temp2[len(temp2) - 1]
temp2.pop()
if abs(x - y) != 1:
result = False
q.put(x)
q.put(y)
if len(temp2) == 1:
q.put(temp2[len(temp2) - 1])
return result
que = [3,4,6,7,8,9]
print(solve(que))

## Input

[3,4,6,7,8,9]

## Output

True