Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class n dimensional vector

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading