jbuser430
jbuser430

Reputation: 101

Vector input gives output vector `[0,...,0]` in Python

I'm trying to create a vector class in Python. I'm not so far yet, and stuck already.

This is my current code:

    class vector:

        def __init__(self, n, l = []):
            self.v = []
            if(isinstance(n, int)):
               x = int(n)
               if (x < 0):
                   return SyntaxError
               else:
                   self.v += [0.0] * x
            else:
               self.v += n

        def __str__(self):
            return str(self.v)

The problem is, that when my input is

    >>> u = vector(3,3.14)
    >>> print(u)

then my ouput is

    [0.0, 0.0, 0.0] 

But I want it to be

    [3.14,3.14,3.14]

and I also want the following:

    >>> v=[3,[2.0,3.14,-5])
    >>> print(v)
    [2.0,3.14,-5]

What is the problem in my script?

Thanks!

Upvotes: 0

Views: 765

Answers (1)

Jieter
Jieter

Reputation: 4229

You have [0.0] * x, but I think you mean [l] * x.

It really helps to clear up what kind of cases your code must support and write it down. It also helps to define a clear list of input and output combinations, you can use them as a test:

class Vector(object):
    def __init__(self, n, l):
        if isinstance(l, (list, tuple)):  # l is a list, check length
            if len(l) == n:  # length as required, keep as is
                pass
            elif len(l) > n:  # to long, use only the first n items
                l = l[0:n]
            elif len(l) < n:  # to short, append zeros
                l += [0] * (n - len(l))

        elif isinstance(l, (int, float)):  # create a list containing n items of l
            l = [l] * n

        self.v = l

    def __str__(self):
        return str(self.v)

Add some tests:

def test(a, b):
    print 'input: {}, output: {}'.format(a, b)
    if str(a) != b:
        print('Not equal!')

test(Vector(3, 3.14), '[3.14, 3.14, 3.14]')
test(Vector(3, [4, 4, 4]), '[4, 4, 4]')
test(Vector(2, [4, 4, 4]), '[4, 4]')
test(Vector(4, [4, 4, 4]), '[4, 4, 4, 0]')
test(Vector(3, [2.0, 3.14, -5]), '[2.0, 3.14, -5]')

Upvotes: 3

Related Questions