Home > OS >  Class n dimensional vector
Class n dimensional vector

Time:12-16

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, )

CodePudding user response:

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: 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:

  • Related