Advertisement
Guest User

python_sparseclass

a guest
Nov 15th, 2015
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. import sparse_functions
  2. class GetAttr(type):
  3.     def __getitem__(cls, x):
  4.         return getattr(cls, x)
  5. class Sparse:
  6.     __metaclass__ = GetAttr
  7.     """ Class for sparse matrices"""
  8.     # This is the constructor when dimensions and sparsity are specified
  9.     def __init__(self, *args):
  10.         # The name of the helper function is sparse_gen
  11.         if len(args) == 3:
  12.             num_row = args[0]
  13.             num_col = args[1]
  14.             spar = args[2]
  15.             if ((type(args[0]) is not int) or (type(args[1]) is not int)):
  16.                 raise TypeError('The first two arguments should be integers!')
  17.             elif not ((args[0] > 0) and (args[1] > 0)):
  18.                 raise ValueError('The first two agruments should be positive!')
  19.             elif not ((args[2] < 1) and (args[2] > 0)):
  20.                 raise ValueError('Sparsity must be between 0 and 1!')
  21.             self.sparse_rep = sparse_functions.sparse_gen(num_row, num_col, spar)
  22.         elif len(args) == 1:
  23.             if (type(args[0] is not list)):
  24.                 raise TypeError('The only argument supplied should be a list!')
  25.             # The list of lists matrix is provided convert it to sparse
  26.             self.sparse_rep = sparse_functions.mat2sparse(arg[0])
  27.         else:
  28.             raise AttributeError('Invalid number of arguments. There should be either one argument or three arguments!')
  29.     # Overload the addition operation
  30.     def __add__(a,b):
  31.         # Here we can make use of the already defined functions
  32.         return sparse_functions.sparse_add(a,b)
  33.     # Overload the subtraction operator
  34.     def __sub__(a,b):
  35.         return sparse_functions.sparse_add(a,-b)
  36.     # Overload the print function
  37.     def __str__(self):
  38.         sparse_functions.sparse_print(self)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement