Class n dimensional vector

Question:

I know how to implement a class for 2n vector.

class vect:
    def __init__(self, *a):
        self.a = a
    def plus(self, *plus):
        res_plus = [vi + wi for vi, wi in zip(self.a, plus)]
        return res_plus
    def minus(self, *minus):
        res_minus = [vi - wi for vi, wi in zip(self.a, minus)]
        return res_minus
    def multiply(self, mult):
        res_multiply = [mult * vi for vi in self.a]
        return res_multiply
x = vect(1,2,3)
print('plus:', x.plus(3,2,1))

It work correct
plus: [4, 4, 4]

But with

x = vect([1,2,3])
print('plus:', x.plus([3,2,1]))

I get plus: [[1, 2, 3, 3, 2, 1]]

How to fix this problem

def convert(list):
    return (*list, )
Asked By: Stephen Brown

||

Answers:

I think you are confusing argument list and starred expressions concepts.

If you don’t want to change your code use unpacking / starred expression when calling your functions:

x = vect(*[1,2,3]) # This syntax means: take the list and pass it as three separate postitional arguments
# So it's literally the same as doing
x = vect(1,2,3)
print('plus:', x.plus(*[3,2,1]))

Take a look at this example:

class A:
   def __init__(self, *a):
      self.a = a # This is going to be a tuple

first = A(1,2,3)
first.a # (1,2,3) three element tuple
second = A([1,2,3]
second.a # ([1,2,3],) one element tuple with a list as the 1st item
third = A([1,2,3], 4)
third.a # ([1,2,3], 4) two element tuple with list as the 1st item and int 4 as 2nd item

Here is a decent answer to similar problem (arguments explained in detail):
https://stackoverflow.com/a/57819001/15923186

Here are docs for argument unpacking:
https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

Not-question related insight:

Answered By: Gameplay
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.