Dec-29-2021, 01:11 PM
For the rotating FIFO, you could use a
collections.deque
instance. You could also very easily implement a fixed length rotating structure with a list and a pointer, for exampleclass Rotating: def __init__(self, items): self.data = list(items) self.head = 0 def __iter__(self): for i in range(len(self)): yield self[i] def __getitem__(self, i): return self.data[(i + self.head) % len(self)] def __len__(self): return len(self.data) def append(self, item): self.data[self.head] = item self.head = (self.head + 1) % len(self) def __str__(self): return 'Rotating({})'.format( self.data[self.head:] + self.data[:self.head]) R = Rotating('abcdef') print(R) R.append('g') print(R) R.append('h') print(R) print(R[0], len(R), R[5]) print(R.data)
Output:Rotating(['a', 'b', 'c', 'd', 'e', 'f'])
Rotating(['b', 'c', 'd', 'e', 'f', 'g'])
Rotating(['c', 'd', 'e', 'f', 'g', 'h'])
c 6 h
['g', 'h', 'c', 'd', 'e', 'f']