0

I'm trying to create a class for a vector, and as such the number of inputs would depend on the dimension of the vector. Here's my code right now:

class vector:
    def __init__(self, entries):
        self.elements = []
        self.dimensionality = len(entries)
        for entry in entries:
            self.elements.append(entry)
    def __str__(self):
        buff = "("
        for e in self.elements:
            buff += str(e)
            if self.elements.index(e) < len(self.elements) - 1:
                buff += ", "
        buff += ")"
        return buff
    def __mul__(self, otherVector):
        if self.dimensionality != otherVector.dimensionality:
            raise RuntimeError("Cannot multiply vectors of different dimensions")
        else:
            product = 0
            for e in self.elements:
                product += e * otherVector.elements[self.elements.index(e)]
            return product
    def __eq__(self, otherVariable):
        return size(self) == size(otherVariable)

def size(x):
    norm = 0
    for e in x.elements:
        norm += e**2
    return norm**(1/2)

As you can see right now I'm just taking a list as an input so I don't have to deal with that, but I want to do matrices next, and that would require a list of lists, which is a pretty tedious way to input information. Anyone know a way to create a class with a flexible number of arguments?

Thanks

Paco Poler
  • 201
  • 1
  • 3
  • 12
  • see http://stackoverflow.com/questions/36901/ –  Nov 27 '15 at 18:37
  • use [`*args` and `**kwargs`](https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=using%20args%20kwargs%20python) – R Nar Nov 27 '15 at 18:37
  • also, classes don't have arguments, methods do –  Nov 27 '15 at 18:38
  • Your entire `__str__` method can be rewritten `'(%s)' % ', '.join(map(str, self.elements))` or even `str(tuple(self.elements))` – Two-Bit Alchemist Nov 27 '15 at 18:41
  • Your entire `__init__` method could be rewritten `self.elements = entries[:]` and you could make `self.dimensionality` a property that returns `len(self.elements)` (which is O(1)). – Two-Bit Alchemist Nov 27 '15 at 18:43
  • The `else` branch of your `__mul__` method (since you're already checking they're the same dimension) could be rewritten `return sum([a*b for a, b in zip(self.elements, otherVector.elements)])` – Two-Bit Alchemist Nov 27 '15 at 18:47
  • Is there a reason you're not using [numpy](http://www.numpy.org/) for this? – Kevin Nov 27 '15 at 18:48

0 Answers0