Question

Python REALLY NEED HELP !!!!!!!!! [10pts] Write the class Vector that supports the basic vector operations....

Python REALLY NEED HELP !!!!!!!!!

[10pts] Write the class Vector that supports the basic vector operations. Such operations are addition (+) and subtraction (-) of vectors of the same length, dot product (*) and multiplication (*) of a vector by a scalar. All methods must return (not print) the result. Your class should also support the rich comparison for equality (==)

  • - You must use the special methods for those 4 operators in order to override their behavior

  • - You will need other special methods to achieve a legible object representation.

  • - Dot product and multiplication by scalar use the same operator, so you must check the type

    of the object in order to decide which operation you have to perform

  • - For addition and subtraction, you must check that vectors have the same length

  • - The dot product results in a scalar, not a Vector

  • - The rest of the methods must return a Vector object (not a string with the word Vector)

  • - Test your code, this is how you ensure you get the most credit out of your work!!

  • - When returning error messages, make sure your string contains the word ‘error’

  • - Check the doctest for object behavior examples. Vector size is variable

  • - Hint: Section 3.3.8. Emulating numeric types in

    https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types

    Deliverables:

class Vector:

'''

>>> Vector([1,2])+Vector([5])

'Error - Invalid dimensions'

>>> Vector([1,2])+Vector([5,2])

Vector([6, 4])

>>> Vector([1,2])-Vector([5,2])

Vector([-4, 0])

>>> Vector([1,2])*Vector([5,2])

9

>>> x=Vector([2,4,6])

>>> y=Vector([2,4,6])

>>> c=x+y

>>> type(c)

<class 'LAB6.Vector'>

>>> print(c)

Vector([4, 8, 12])

>>> x==y

True

>>> x-Vector([1,2])

'Error - Invalid dimensions'

>>> x+5

'Error - Invalid operation'

>>> x*y

56

>>> x*5

Vector([10, 20, 30])

>>> 5*x

Vector([10, 20, 30])

'''

def __init__(self, vector_list):

self.vector = vector_list

# --- Your code starts here

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

#code

class Vector:

    '''

    >>> Vector([1,2])+Vector([5])

    'Error - Invalid dimensions'

    >>> Vector([1,2])+Vector([5,2])

    Vector([6, 4])

    >>> Vector([1,2])-Vector([5,2])

    Vector([-4, 0])

    >>> Vector([1,2])*Vector([5,2])

    9

    >>> x=Vector([2,4,6])

    >>> y=Vector([2,4,6])

    >>> c=x+y

    >>> type(c)

    <class 'LAB6.Vector'>

    >>> print(c)

    Vector([4, 8, 12])

    >>> x==y

    True

    >>> x-Vector([1,2])

    'Error - Invalid dimensions'

    >>> x+5

    'Error - Invalid operation'

    >>> x*y

    56

    >>> x*5

    Vector([10, 20, 30])

    >>> 5*x

    Vector([10, 20, 30])

    '''

    def __init__(self, vector_list):

        self.vector = vector_list

    #returns the length of underlying list as the length of vector

    def __len__(self):

        return len(self.vector)

    #returns a string containing vector contents

    def __repr__(self):

        return 'Vector('+repr(self.vector)+')'

    #adds two vectors (+ operator)

    def __add__(self, other):

        if type(other)!=Vector:

            #invalid operand

            return 'Error - Invalid operation'

        elif len(self)==len(other):

            #same length, creating an empty list

            res=[]

            #adding corresponding elements of this vector and other, appending to res

            for i in range(len(self)):

                res.append(self.vector[i]+other.vector[i])

            return Vector(res) #creating a Vector with values in res, and returns it

        return 'Error - Invalid dimensions' #invalid lengths

    #subtracts two vectors (- operator)

    def __sub__(self, other):

        if type(other)==Vector and len(self)==len(other):

            res=[]

            for i in range(len(self)):

                res.append(self.vector[i]-other.vector[i])

            return Vector(res)

        return 'Error - Invalid dimensions'

    #multiplies two vectors or finds scalar product based on type of other

    def __mul__(self, other):

        #checking if other type is int

        if type(other)==int:

            res=[]

            #returning scalar product

            for i in self.vector:

                res.append(i*other)

            return Vector(res)

        elif type(other)==Vector:

            #returning dot product if lengths are same

            if len(self)==len(other):

                dot_product=0

                for i in range(len(self)):

                    dot_product+=(self.vector[i]*other.vector[i])

                return dot_product

            else:

                return 'Error - Invalid dimensions'#invalid lengths

        else:

            return 'Error - Invalid operation' #invalid other type

    #same as multiplication, but calls when this vector object is in right side of

    #the * operator (example: vector*5 is __mul__, 5*vector is __rmul__)

    def __rmul__(self, other):

        return self.__mul__(other)

    #compares two vectors

    def __eq__(self, other):

        if type(other)==Vector:

            if len(self)!=len(other):

                #lengths mismatch

                return False

            for i in range(len(self)):

                if self.vector[i]!=other.vector[i]:

                    return False #elements mismatch

            return True #all elements checks out

        return False #type mismatch

#output (of doctest)

Add a comment
Know the answer?
Add Answer to:
Python REALLY NEED HELP !!!!!!!!! [10pts] Write the class Vector that supports the basic vector operations....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • implement a C++ class name Vector. The Vector class contains a private double array of length...

    implement a C++ class name Vector. The Vector class contains a private double array of length 2 named elements that represents a two-dimensional vector. We will also implement an overloaded multiplication operator (*) that accepts a single Vector variable by reference and returns the Dot Product between the current Vector object and the one pointed to by the function argument in form of a double. Please recall that the dot product of two vectors a =(21,92) and 5 = (b1,b2)...

  • please help me. than A vector A^rightarrow has a magnitude of 9 units and points in...

    please help me. than A vector A^rightarrow has a magnitude of 9 units and points in the -y direction, while a vector B^rightarrow has double the magnitude of A^rightarrow and points in the +x direction. What are the magnitude and direction of the following vectors? Give the directions of each as an angle measured counterclockwise from the +x direction. A^rightarrow + B^rightarrow magnitude unit(s) direction Use trigonometric functions to determine the angle. Check this angle against your diagram. Based on...

  • T Programming for Math and Science Lab 4 March 25 and 28, 2019. Instructions: Write a module vect...

    Please answer question #2, which means the methods for vector addition, negation and subtraction. t Programming for Math and Science Lab 4 March 25 and 28, 2019. Instructions: Write a module vector.py (but submitted as LastNameFirst Name.Lab4.py) w hich im- plements the dictionary based representation Vector elass, Send to rryhame fordham.edu March 31, 11:59 p.m. Please subanit on.time as the syllabus's no late work policy will henceforth be in force. The gonl is to create the following class object class...

  • 7. Average age in a population. Suppose the 100-vector a represents the distribution of ages in a population, with xi b...

    7. Average age in a population. Suppose the 100-vector a represents the distribution of ages in a population, with xi being the number of i-1 year olds, for i = 1, . . . , 100. Find an expression for the average age across the population. (You can assume that xメ0) Your expression must use vector or matrix notation; you cannot use a sum over ages You can use any notation we've encountered, including vectors, matrices, matrix-vector products, inner product,...

  • 6 ture Supplement 4: Intro Vectors Worksheet B a vector (graphical, verbal, or mathematical) that is...

    6 ture Supplement 4: Intro Vectors Worksheet B a vector (graphical, verbal, or mathematical) that is in: Provide an example of a) ID b) 2D c) 3D (graphi Outline the main vector operations we will use in class: a) Vector Addition b) Vector Subtraction c) Scalar Multiplication d) Vector Dot Product e) Vector Cross Product What is a resultant vector? 4 What is the component of a vector? 3,Define a unit vector. Give an example of a unit vector in...

  • Need help solving these please Write the vector shown above as a linear combination of 7...

    Need help solving these please Write the vector shown above as a linear combination of 7 and 3. Vector * { + j Note: In the graph, each box is 1 unit by 1 unit in size. A vector with magnitude 7 points in a direction 265 degrees counterclockwise from the positive x axis. Write the vector in component form, and show your answers accurate to 3 decimal places. Vector Given = 57 + 4j and p=6i + 3, find...

  • Write a code in java by considering the following conditions. Task :- 1. Design, implement and test a class RationalNumber. 2. Your class must have a constructor. 3. Your class must implement an inter...

    Write a code in java by considering the following conditions. Task :- 1. Design, implement and test a class RationalNumber. 2. Your class must have a constructor. 3. Your class must implement an interface Number that has methods to perform different operations on a rational numbers (addition, subtraction, reciprocal, multiplication and division). 4. Also design some methods to check whether two rational numbers are same or not (consider numbers are in reduced form). 5. You must develop an appropriate GUI...

  • 6. 2D vectors Lec ture Supplement 4: Intro Vectors Worksheet B Provide an example of a)...

    6. 2D vectors Lec ture Supplement 4: Intro Vectors Worksheet B Provide an example of a) ID b) 2D c) 3D a vector (graphical, verbal, or mathematical) that is in: (graphi Outline the main vector operations we will use in class: a) Vector Addition b) Vector Subtraction c) Scalar Multiplication d) Vector Dot Product e) Vector Cross Product What is a resultant vector? 4 What is the component of a vector? &Define a unit vector. Give an example of a...

  • 7. Lec ture Supplement 4: Intro Vectors Worksheet B Provide an example of a) ID b)...

    7. Lec ture Supplement 4: Intro Vectors Worksheet B Provide an example of a) ID b) 2D c) 3D a vector (graphical, verbal, or mathematical) that is in: (graphi Outline the main vector operations we will use in class: a) Vector Addition b) Vector Subtraction c) Scalar Multiplication d) Vector Dot Product e) Vector Cross Product What is a resultant vector? 4 What is the component of a vector? &Define a unit vector. Give an example of a unit vector...

  • Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public...

    Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public class Matrix3 { private double[][] matrix; /** * Creates a 3x3 matrix from an 2D array * @param v array containing 3 components of the desired vector */ public Matrix3(double[][] array) { this.matrix = array; } /** * Clones an existing matrix * @param old an existing Matrix3 object */ public Matrix3(Matrix3 old) { matrix = new double[old.matrix.length][]; for(int i = 0; i <...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT