📘
Magic Methods
MediumPython OOP
Problem Statement
Implement a Vector class with magic methods for arithmetic operations.
Background
Python magic methods enable operator overloading:
- add: + operator
- sub: - operator
- mul: * operator (scalar)
- eq: == operator
- len: len() function
Your Task
Create a Vector class that supports:
- Addition: v1 + v2 (element-wise)
- Subtraction: v1 - v2 (element-wise)
- Scalar multiplication: v * scalar
- Equality: v1 == v2
- Length: len(v) returns number of elements
- str: "Vector([...])"
Example:
Input:
Vector([1, 2, 3]) + Vector([4, 5, 6])
Output:
Vector([5, 7, 9])
Reasoning:
Element-wise: 1+4=5, 2+5=7, 3+6=9
Constraints:
- Vectors for arithmetic must have same length
- Return new Vector objects, don't modify originals
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.