Circular Array

7.9 Circular Array: Implement a CircularArray class that supports an array-like data structure which can be efficiently rotated. If possible, the class should use a generic type (also called a template), and should support iteration via the standard for (Obj 0 : circularArray) notation.

The Idea: Override/redefine the iterater methods, and maintain a counter that mods off the array size.

Complexity: O(1) retrival methods

class CircularArray:
    def __init__(self, ar, start):
        """
        :param ar: List[<type>] - iterable list
        :param start: [int] - start of iteration, zero indexed
        """
        self.ar = ar
        self.length = len(ar)
        self.iter = start
        self.remainder = len(ar)

    def __iter__(self):
        return self

    def __next__(self):
        """
        :return: next iterable it exists, otherwise
                 and exception gets raised
        """
        if self.remainder == 0:
            raise StopIteration
        else:
            self.iter += 1
            self.remainder -= 1
            return self.ar[(self.iter - 1) % self.length]


# interally the exceptions gets caught in the ranged loop
ca = CircularArray([1,2,3,4,5], 2)
for num in ca:
    print(num, end=' ')

Last updated