Program to design a queue that moves the most recently used element to the end of it in Python

PythonServer Side ProgrammingProgramming

Suppose, we are asked to design a queue that moves the most recently used element to the end of it. The queue will be initialized with integer numbers 1 to n. Now we have to build a function so that whenever it is called, it moves the value from the position given as its input to the end of the queue. We will call the function multiple times, and the function will return the value currently at the end of the queue while performing its moving task.

So, if the queue is initialized with a value n = 5, or it contains values from 1 to 5.; and the positions where the move is performed are 5, 2, 3, and 1 respectively, then the output will be 5, 2, 4, 1

To solve this, we will follow these steps −

  • i := the position in array index - 1, where the value k can be inserted to the right of maintaining the sorted order
  • x := delete (k - index[i])th element from data[i]
  • for ii in range i+1 to size of index, do
    • index[ii] := index[ii] - 1
  • if size of last element of data>= nn, then
    • insert a new list at the end of list data
    • insert n at the end of list index
  • insert x at the end of data
  • if data[i] is rmpty, then
    • delete ith element from data
    • delete ith element from index
  • return x

Example

Let us see the following implementation to get better understanding −

from bisect import bisect_right
from math import sqrt
class TestQueue:
   def __init__(self, n):
      self.n = n
      self.nn = int(sqrt(n))
      self.data = []
      self.index = []
      for i in range(1, n+1):
         ii = (i-1)//self.nn
         if ii == len(self.data):
            self.data.append([])
            self.index.append(i)
         self.data[-1].append(i)

   def solve(self, k):
      i = bisect_right(self.index, k)-1
      x = self.data[i].pop(k - self.index[i])
      for ii in range(i+1, len(self.index)):
         self.index[ii] -= 1
      if len(self.data[-1]) >= self.nn:
         self.data.append([])
         self.index.append(self.n)
      self.data[-1].append(x)
      if not self.data[i]:
         self.data.pop(i)
         self.index.pop(i)
      return x

queue = TestQueue(5)
print(queue.solve(5))
print(queue.solve(2))
print(queue.solve(3))
print(queue.solve(1))

Input

queue = TestQueue(5)
print(queue.solve(5))
print(queue.solve(2))
print(queue.solve(3))
print(queue.solve(1))

Output

5
2
4
1
raja
Published on 07-Oct-2021 11:49:46
Advertisements