Welcome, guest | Sign In | My Account | Store | Cart

ShiftMatrix is a class that generates matrix values by shifting the zeroth row left or right length_of_row times. For example: if you initialize it with sm = ShiftMatrix([1,2,3]), sm[1] will return [3,1,2]. Only the initial list is stored, the other values are generated at runtime.

Python, 62 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class ShiftMatrix(object):
    """ An NxN matrix generated by shifting the zeroth row left or right.
    Only the zeroth row is stored in memory, the rest is generated. This
    cuts memory usage from NxN to a single N.

    >>> shift_matrix = ShiftMatrix([1, 2, 3, 4])
    >>> print shift_matrix
    [1, 2, 3, 4]
    [4, 1, 2, 3]
    [3, 4, 1, 2]
    [2, 3, 4, 1]

    >>> shift_matrix = ShiftMatrix([1, 2, 3, 4])
    >>> print len(shift_matrix)
    16

    The class works with any iterable, for example a string:
    >>> shift_matrix = ShiftMatrix('Test', shift='left')
    >>> print shift_matrix[1]
    estT

    >>> shift_matrix = ShiftMatrix('Test', shift='left')
    >>> print shift_matrix[1][2]
    t
    """

    def __init__(self, data=None, shift='right'):
        if shift in ['right','left']:
            self.shift = shift
        else:
            raise ValueError("Shift direction must be 'right' or 'left'.")
        if not data:
            self.data = list()
        else:
            try:
                iter(data)
            except TypeError, e:
                raise TypeError("Object is not iterable.")
            self.data = data

    def __getitem__(self, index):
        if index > len(self.data) - 1:
            raise IndexError("Object has no index %d." % index)
        if self.shift == 'right':
            return self.data[-index % len(self.data):] + self.data[:-index]
        if self.shift == 'left':
            return self.data[index:] + self.data[:index % len(self.data)]

    def __len__(self):
        return len(self.data)

    def __str__(self):
        return "\n".join(str(row) for row in self.__iter__())

    def __iter__(self):
        for row_index in range(len(self.data)):
            yield self.__getitem__(row_index)

if __name__ == "__main__":
    shift_matrix = ShiftMatrix([1,2,3],shift='left')
    for row in shift_matrix:
        print row
Created by Andrej T. on Sun, 3 Jun 2012 (MIT)
Python recipes (4591)
Andrej T.'s recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks