class Vector: """Represent a vector in a multidimensional space.""" def __init__(self, d): """Create d-dimensional vector of zeros.""" self._coords = [0] * d def __len__(self): """Return the dimension of the vector.""" return len(self._coords) def __getitem__(self, j): """Return jth coordinate of vector.""" return self._coords[j] def __getattr__(self, j, val): """Set jth coordinate of vector to given value.""" self._coords[j] = val def __add__(self, other): """Return sum of two vectors.""" if len(self) != len(other): # relies on len method raise ValueError("dimensions must agree") result = Vector(len(self)) # start with vector of zeros for j in range(len(self)): result[j] = self[j] + other[j] return result def __eq__(self, other): """Return True if vector has same coordinates as other.""" return self._coords == other._coords def __ne__(self, other): """Return True if vector differs from other.""" return not self == other # rely on existing eq definition def __str__(self): """Produce string representation of vector.""" return '<' + str(self._coords)[1:-1] + '>' # adapt list representation def __mul__(self, other): """Produce product of vector and int m and return said product.""" print("I'm being called!") v = Vector(len(self)) for i in range(len(self)): # v[i] = self[i] * m # print(self[i]) v[0] = self[i] * self return v print("----- R-2.13 -----") v1 = Vector(3) # Vector is now (0,0,0) v2 = Vector(3) v1 = (1, 2, 3) v2 = (2, 3, 4) v2 = v1 * 4 print(v2) # Expected: (4, 8. 12)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question