updates for chapter 11
This commit is contained in:
parent
ca049e9a3f
commit
661b68b235
3
.gitignore
vendored
3
.gitignore
vendored
@ -55,3 +55,6 @@ docs/_build/
|
|||||||
|
|
||||||
# PyBuilder
|
# PyBuilder
|
||||||
target/
|
target/
|
||||||
|
|
||||||
|
# PyCharm
|
||||||
|
.idea/
|
||||||
|
85
classes/sum-nth-element.rst
Normal file
85
classes/sum-nth-element.rst
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
======================================
|
||||||
|
Pythonic way to sum n-th list element?
|
||||||
|
======================================
|
||||||
|
|
||||||
|
Examples inspired by Guy Middleton's question on Python-list, Fri Apr 18 22:21:08 CEST 2003. Message: https://mail.python.org/pipermail/python-list/2003-April/218568.html
|
||||||
|
|
||||||
|
Guy Middleton::
|
||||||
|
|
||||||
|
>>> my_list = [[1, 2, 3], [40, 50, 60], [9, 8, 7]]
|
||||||
|
>>> import functools as ft
|
||||||
|
>>> ft.reduce(lambda a, b: a+b, [sub[1] for sub in my_list])
|
||||||
|
60
|
||||||
|
|
||||||
|
LR::
|
||||||
|
|
||||||
|
>>> ft.reduce(lambda a, b: a + b[1], my_list, 0)
|
||||||
|
60
|
||||||
|
|
||||||
|
Fernando Perez::
|
||||||
|
|
||||||
|
>>> import numpy as np
|
||||||
|
>>> my_array = np.array(my_list)
|
||||||
|
>>> np.sum(my_array[:, 1])
|
||||||
|
60
|
||||||
|
|
||||||
|
Skip Montanaro::
|
||||||
|
|
||||||
|
>>> import operator
|
||||||
|
>>> ft.reduce(operator.add, [sub[1] for sub in my_list], 0)
|
||||||
|
60
|
||||||
|
>>> ft.reduce(operator.add, [sub[1] for sub in []])
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: reduce() of empty sequence with no initial value
|
||||||
|
>>> ft.reduce(operator.add, [sub[1] for sub in []], 0)
|
||||||
|
0
|
||||||
|
|
||||||
|
|
||||||
|
Evan Simpson::
|
||||||
|
|
||||||
|
>>> total = 0
|
||||||
|
>>> for sub in my_list:
|
||||||
|
... total += sub[1]
|
||||||
|
>>> total
|
||||||
|
60
|
||||||
|
|
||||||
|
Alex Martelli (``sum`` was added in Python 2.3, released July 9, 2003)::
|
||||||
|
|
||||||
|
>>> sum([sub[1] for sub in my_list])
|
||||||
|
60
|
||||||
|
|
||||||
|
After generator expressions (added in Python 2.4, November 30, 2004)::
|
||||||
|
|
||||||
|
>>> sum(sub[1] for sub in my_list)
|
||||||
|
60
|
||||||
|
|
||||||
|
If you want the sum of a list of items, you should write it in a way
|
||||||
|
that looks like "the sum of a list of items", not in a way that looks
|
||||||
|
like "loop over these items, maintain another variable t, perform a
|
||||||
|
sequence of additions". Why do we have high level languages if not to
|
||||||
|
express our intentions at a higher level and let the language worry
|
||||||
|
about what low-level operations are needed to implement it?
|
||||||
|
|
||||||
|
David Eppstein
|
||||||
|
|
||||||
|
Alex Martelli
|
||||||
|
|
||||||
|
https://mail.python.org/pipermail/python-list/2003-April/186311.html
|
||||||
|
|
||||||
|
"The sum" is so frequently needed that I wouldn't mind at all if
|
||||||
|
Python singled it out as a built-in. But "reduce(operator.add, ..."
|
||||||
|
just isn't a great way to express it, in my opinion (and yet as an
|
||||||
|
old APL'er, and FP-liker, I _should_ like it -- but I don't).
|
||||||
|
|
||||||
|
https://mail.python.org/pipermail/python-list/2003-April/225323.html
|
||||||
|
|
||||||
|
Four years later, having coded a lot of Python, taught it widely,
|
||||||
|
written a lot about it, and so on, I've changed my mind: I now
|
||||||
|
think that reduce is more trouble than it's worth and Python
|
||||||
|
would be better off without it, if it was being designed from
|
||||||
|
scratch today -- it would not substantially reduce (:-) Python's
|
||||||
|
power and WOULD substantially ease the teaching/&c task. That's
|
||||||
|
not a strong-enough argument to REMOVE a builtin, of course, and
|
||||||
|
thus that's definitely NOT what I'm arguing for. But I do suggest
|
||||||
|
avoiding reduce in most cases -- that's all.
|
@ -26,7 +26,7 @@ Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
|||||||
(3.0, 4.0)
|
(3.0, 4.0)
|
||||||
>>> octets = bytes(v1)
|
>>> octets = bytes(v1)
|
||||||
>>> octets
|
>>> octets
|
||||||
b'\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||||
>>> abs(v1)
|
>>> abs(v1)
|
||||||
5.0
|
5.0
|
||||||
>>> bool(v1), bool(Vector([0, 0]))
|
>>> bool(v1), bool(Vector([0, 0]))
|
||||||
@ -106,7 +106,8 @@ class Vector:
|
|||||||
return str(tuple(self))
|
return str(tuple(self))
|
||||||
|
|
||||||
def __bytes__(self):
|
def __bytes__(self):
|
||||||
return bytes(self._components) # <5>
|
return (bytes([ord(self.typecode)]) +
|
||||||
|
bytes(self._components)) # <5>
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return tuple(self) == tuple(other)
|
return tuple(self) == tuple(other)
|
||||||
@ -119,6 +120,7 @@ class Vector:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def frombytes(cls, octets):
|
def frombytes(cls, octets):
|
||||||
memv = memoryview(octets).cast(cls.typecode)
|
typecode = chr(octets[0])
|
||||||
|
memv = memoryview(octets[1:]).cast(typecode)
|
||||||
return cls(memv) # <7>
|
return cls(memv) # <7>
|
||||||
# END VECTOR_V1
|
# END VECTOR_V1
|
||||||
|
@ -26,7 +26,7 @@ Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
|||||||
(3.0, 4.0)
|
(3.0, 4.0)
|
||||||
>>> octets = bytes(v1)
|
>>> octets = bytes(v1)
|
||||||
>>> octets
|
>>> octets
|
||||||
b'\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||||
>>> abs(v1)
|
>>> abs(v1)
|
||||||
5.0
|
5.0
|
||||||
>>> bool(v1), bool(Vector([0, 0]))
|
>>> bool(v1), bool(Vector([0, 0]))
|
||||||
@ -132,7 +132,8 @@ class Vector:
|
|||||||
return str(tuple(self))
|
return str(tuple(self))
|
||||||
|
|
||||||
def __bytes__(self):
|
def __bytes__(self):
|
||||||
return bytes(self._components)
|
return (bytes([ord(self.typecode)]) +
|
||||||
|
bytes(self._components))
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return tuple(self) == tuple(other)
|
return tuple(self) == tuple(other)
|
||||||
@ -160,5 +161,6 @@ class Vector:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def frombytes(cls, octets):
|
def frombytes(cls, octets):
|
||||||
memv = memoryview(octets).cast(cls.typecode)
|
typecode = chr(octets[0])
|
||||||
|
memv = memoryview(octets[1:]).cast(typecode)
|
||||||
return cls(memv)
|
return cls(memv)
|
||||||
|
@ -26,7 +26,7 @@ Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
|||||||
(3.0, 4.0)
|
(3.0, 4.0)
|
||||||
>>> octets = bytes(v1)
|
>>> octets = bytes(v1)
|
||||||
>>> octets
|
>>> octets
|
||||||
b'\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||||
>>> abs(v1)
|
>>> abs(v1)
|
||||||
5.0
|
5.0
|
||||||
>>> bool(v1), bool(Vector([0, 0]))
|
>>> bool(v1), bool(Vector([0, 0]))
|
||||||
@ -109,8 +109,9 @@ Tests of dynamic attribute access::
|
|||||||
>>> v7 = Vector(range(10))
|
>>> v7 = Vector(range(10))
|
||||||
>>> v7.x
|
>>> v7.x
|
||||||
0.0
|
0.0
|
||||||
>>> v7.y, v7.z, v7.t, v7.u, v7.v, v7.w
|
>>> v7.y, v7.z, v7.t
|
||||||
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
|
(1.0, 2.0, 3.0)
|
||||||
|
|
||||||
|
|
||||||
Dynamic attribute lookup failures::
|
Dynamic attribute lookup failures::
|
||||||
|
|
||||||
@ -129,6 +130,26 @@ Dynamic attribute lookup failures::
|
|||||||
AttributeError: 'Vector' object has no attribute 'spam'
|
AttributeError: 'Vector' object has no attribute 'spam'
|
||||||
|
|
||||||
|
|
||||||
|
Tests of preventing attributes from 'a' to 'z'::
|
||||||
|
|
||||||
|
>>> v1.x = 7
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
AttributeError: readonly attribute 'x'
|
||||||
|
>>> v1.w = 7
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
AttributeError: can't set attributes 'a' to 'z' in 'Vector'
|
||||||
|
|
||||||
|
Other attributes can be set::
|
||||||
|
|
||||||
|
>>> v1.X = 'albatross'
|
||||||
|
>>> v1.X
|
||||||
|
'albatross'
|
||||||
|
>>> v1.ni = 'Ni!'
|
||||||
|
>>> v1.ni
|
||||||
|
'Ni!'
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from array import array
|
from array import array
|
||||||
@ -154,7 +175,8 @@ class Vector:
|
|||||||
return str(tuple(self))
|
return str(tuple(self))
|
||||||
|
|
||||||
def __bytes__(self):
|
def __bytes__(self):
|
||||||
return bytes(self._components)
|
return (bytes([ord(self.typecode)]) +
|
||||||
|
bytes(self._components))
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return tuple(self) == tuple(other)
|
return tuple(self) == tuple(other)
|
||||||
@ -178,8 +200,8 @@ class Vector:
|
|||||||
msg = '{.__name__} indices must be integers'
|
msg = '{.__name__} indices must be integers'
|
||||||
raise TypeError(msg.format(cls))
|
raise TypeError(msg.format(cls))
|
||||||
|
|
||||||
# BEGIN VECTOR_V3
|
# BEGIN VECTOR_V3_GETATTR
|
||||||
shortcut_names = 'xyztuvw'
|
shortcut_names = 'xyzt'
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
cls = type(self) # <1>
|
cls = type(self) # <1>
|
||||||
@ -190,9 +212,27 @@ class Vector:
|
|||||||
msg = '{.__name__!r} object has no attribute {!r}' # <5>
|
msg = '{.__name__!r} object has no attribute {!r}' # <5>
|
||||||
raise AttributeError(msg.format(cls, name))
|
raise AttributeError(msg.format(cls, name))
|
||||||
|
|
||||||
# END VECTOR_V3
|
# END VECTOR_V3_GETATTR
|
||||||
|
# BEGIN VECTOR_V3_SETATTR
|
||||||
|
def __setattr__(self, name, value):
|
||||||
|
cls = type(self)
|
||||||
|
if len(name) == 1: # <1>
|
||||||
|
if name in cls.shortcut_names: # <2>
|
||||||
|
error = 'readonly attribute {attr_name!r}'
|
||||||
|
elif name.islower(): # <3>
|
||||||
|
error = "can't set attributes 'a' to 'z' in {cls_name!r}"
|
||||||
|
else:
|
||||||
|
error = '' # <4>
|
||||||
|
if error: # <5>
|
||||||
|
msg = error.format(cls_name=cls.__name__, attr_name=name)
|
||||||
|
raise AttributeError(msg)
|
||||||
|
super().__setattr__(name, value) # <6>
|
||||||
|
|
||||||
|
# END VECTOR_V3_SETATTR
|
||||||
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def frombytes(cls, octets):
|
def frombytes(cls, octets):
|
||||||
memv = memoryview(octets).cast(cls.typecode)
|
typecode = chr(octets[0])
|
||||||
|
memv = memoryview(octets[1:]).cast(typecode)
|
||||||
return cls(memv)
|
return cls(memv)
|
||||||
|
@ -26,7 +26,7 @@ Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
|||||||
(3.0, 4.0)
|
(3.0, 4.0)
|
||||||
>>> octets = bytes(v1)
|
>>> octets = bytes(v1)
|
||||||
>>> octets
|
>>> octets
|
||||||
b'\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||||
>>> abs(v1)
|
>>> abs(v1)
|
||||||
5.0
|
5.0
|
||||||
>>> bool(v1), bool(Vector([0, 0]))
|
>>> bool(v1), bool(Vector([0, 0]))
|
||||||
@ -109,8 +109,8 @@ Tests of dynamic attribute access::
|
|||||||
>>> v7 = Vector(range(10))
|
>>> v7 = Vector(range(10))
|
||||||
>>> v7.x
|
>>> v7.x
|
||||||
0.0
|
0.0
|
||||||
>>> v7.y, v7.z, v7.t, v7.u, v7.v, v7.w
|
>>> v7.y, v7.z, v7.t
|
||||||
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
|
(1.0, 2.0, 3.0)
|
||||||
|
|
||||||
Dynamic attribute lookup failures::
|
Dynamic attribute lookup failures::
|
||||||
|
|
||||||
@ -168,14 +168,16 @@ class Vector:
|
|||||||
return str(tuple(self))
|
return str(tuple(self))
|
||||||
|
|
||||||
def __bytes__(self):
|
def __bytes__(self):
|
||||||
return bytes(self._components)
|
return (bytes([ord(self.typecode)]) +
|
||||||
|
bytes(self._components))
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return tuple(self) == tuple(other)
|
return (len(self) == len(other) and
|
||||||
|
all(a == b for a, b in zip(self, other)))
|
||||||
|
|
||||||
def __hash__(self):
|
def __hash__(self):
|
||||||
hashes = (hash(x) for x in self)
|
hashes = (hash(x) for x in self)
|
||||||
return functools.reduce(operator.xor, hashes)
|
return functools.reduce(operator.xor, hashes, 0)
|
||||||
|
|
||||||
def __abs__(self):
|
def __abs__(self):
|
||||||
return math.sqrt(sum(x * x for x in self))
|
return math.sqrt(sum(x * x for x in self))
|
||||||
@ -196,7 +198,7 @@ class Vector:
|
|||||||
msg = '{.__name__} indices must be integers'
|
msg = '{.__name__} indices must be integers'
|
||||||
raise TypeError(msg.format(cls))
|
raise TypeError(msg.format(cls))
|
||||||
|
|
||||||
shortcut_names = 'xyztuvw'
|
shortcut_names = 'xyzt'
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
cls = type(self) # <1>
|
cls = type(self) # <1>
|
||||||
@ -209,5 +211,6 @@ class Vector:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def frombytes(cls, octets):
|
def frombytes(cls, octets):
|
||||||
memv = memoryview(octets).cast(cls.typecode)
|
typecode = chr(octets[0])
|
||||||
|
memv = memoryview(octets[1:]).cast(typecode)
|
||||||
return cls(memv)
|
return cls(memv)
|
||||||
|
@ -27,7 +27,7 @@ Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
|||||||
(3.0, 4.0)
|
(3.0, 4.0)
|
||||||
>>> octets = bytes(v1)
|
>>> octets = bytes(v1)
|
||||||
>>> octets
|
>>> octets
|
||||||
b'\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||||
>>> abs(v1)
|
>>> abs(v1)
|
||||||
5.0
|
5.0
|
||||||
>>> bool(v1), bool(Vector([0, 0]))
|
>>> bool(v1), bool(Vector([0, 0]))
|
||||||
@ -110,8 +110,8 @@ Tests of dynamic attribute access::
|
|||||||
>>> v7 = Vector(range(10))
|
>>> v7 = Vector(range(10))
|
||||||
>>> v7.x
|
>>> v7.x
|
||||||
0.0
|
0.0
|
||||||
>>> v7.y, v7.z, v7.t, v7.u, v7.v, v7.w
|
>>> v7.y, v7.z, v7.t
|
||||||
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
|
(1.0, 2.0, 3.0)
|
||||||
|
|
||||||
Dynamic attribute lookup failures::
|
Dynamic attribute lookup failures::
|
||||||
|
|
||||||
@ -210,14 +210,16 @@ class Vector:
|
|||||||
return str(tuple(self))
|
return str(tuple(self))
|
||||||
|
|
||||||
def __bytes__(self):
|
def __bytes__(self):
|
||||||
return bytes(self._components)
|
return (bytes([ord(self.typecode)]) +
|
||||||
|
bytes(self._components))
|
||||||
|
|
||||||
def __eq__(self, other):
|
def __eq__(self, other):
|
||||||
return tuple(self) == tuple(other)
|
return (len(self) == len(other) and
|
||||||
|
all(a == b for a, b in zip(self, other)))
|
||||||
|
|
||||||
def __hash__(self):
|
def __hash__(self):
|
||||||
hashes = (hash(x) for x in self)
|
hashes = (hash(x) for x in self)
|
||||||
return functools.reduce(operator.xor, hashes)
|
return functools.reduce(operator.xor, hashes, 0)
|
||||||
|
|
||||||
def __abs__(self):
|
def __abs__(self):
|
||||||
return math.sqrt(sum(x * x for x in self))
|
return math.sqrt(sum(x * x for x in self))
|
||||||
@ -238,7 +240,7 @@ class Vector:
|
|||||||
msg = '{.__name__} indices must be integers'
|
msg = '{.__name__} indices must be integers'
|
||||||
raise TypeError(msg.format(cls))
|
raise TypeError(msg.format(cls))
|
||||||
|
|
||||||
shortcut_names = 'xyztuvw'
|
shortcut_names = 'xyzt'
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
cls = type(self)
|
cls = type(self)
|
||||||
@ -274,6 +276,7 @@ class Vector:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def frombytes(cls, octets):
|
def frombytes(cls, octets):
|
||||||
memv = memoryview(octets).cast(cls.typecode)
|
typecode = chr(octets[0])
|
||||||
|
memv = memoryview(octets[1:]).cast(typecode)
|
||||||
return cls(memv)
|
return cls(memv)
|
||||||
# END VECTOR_V5
|
# END VECTOR_V5
|
||||||
|
308
classes/vector_v6.py
Normal file
308
classes/vector_v6.py
Normal file
@ -0,0 +1,308 @@
|
|||||||
|
"""
|
||||||
|
A multi-dimensional ``Vector`` class, take 6
|
||||||
|
|
||||||
|
A ``Vector`` is built from an iterable of numbers::
|
||||||
|
|
||||||
|
>>> Vector([3.1, 4.2])
|
||||||
|
Vector([3.1, 4.2])
|
||||||
|
>>> Vector((3, 4, 5))
|
||||||
|
Vector([3.0, 4.0, 5.0])
|
||||||
|
>>> Vector(range(10))
|
||||||
|
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||||
|
|
||||||
|
|
||||||
|
Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
||||||
|
|
||||||
|
>>> v1 = Vector([3, 4])
|
||||||
|
>>> x, y = v1
|
||||||
|
>>> x, y
|
||||||
|
(3.0, 4.0)
|
||||||
|
>>> v1
|
||||||
|
Vector([3.0, 4.0])
|
||||||
|
>>> v1_clone = eval(repr(v1))
|
||||||
|
>>> v1 == v1_clone
|
||||||
|
True
|
||||||
|
>>> print(v1)
|
||||||
|
(3.0, 4.0)
|
||||||
|
>>> octets = bytes(v1)
|
||||||
|
>>> octets
|
||||||
|
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||||
|
>>> abs(v1)
|
||||||
|
5.0
|
||||||
|
>>> bool(v1), bool(Vector([0, 0]))
|
||||||
|
(True, False)
|
||||||
|
|
||||||
|
|
||||||
|
Test of ``.frombytes()`` class method:
|
||||||
|
|
||||||
|
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||||
|
>>> v1_clone
|
||||||
|
Vector([3.0, 4.0])
|
||||||
|
>>> v1 == v1_clone
|
||||||
|
True
|
||||||
|
|
||||||
|
|
||||||
|
Tests with 3-dimensions::
|
||||||
|
|
||||||
|
>>> v1 = Vector([3, 4, 5])
|
||||||
|
>>> x, y, z = v1
|
||||||
|
>>> x, y, z
|
||||||
|
(3.0, 4.0, 5.0)
|
||||||
|
>>> v1
|
||||||
|
Vector([3.0, 4.0, 5.0])
|
||||||
|
>>> v1_clone = eval(repr(v1))
|
||||||
|
>>> v1 == v1_clone
|
||||||
|
True
|
||||||
|
>>> print(v1)
|
||||||
|
(3.0, 4.0, 5.0)
|
||||||
|
>>> abs(v1) # doctest:+ELLIPSIS
|
||||||
|
7.071067811...
|
||||||
|
>>> bool(v1), bool(Vector([0, 0, 0]))
|
||||||
|
(True, False)
|
||||||
|
|
||||||
|
|
||||||
|
Tests with many dimensions::
|
||||||
|
|
||||||
|
>>> v7 = Vector(range(7))
|
||||||
|
>>> v7
|
||||||
|
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||||
|
>>> abs(v7) # doctest:+ELLIPSIS
|
||||||
|
9.53939201...
|
||||||
|
|
||||||
|
|
||||||
|
Test of ``.__bytes__`` and ``.frombytes()`` methods::
|
||||||
|
|
||||||
|
>>> v1 = Vector([3, 4, 5])
|
||||||
|
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||||
|
>>> v1_clone
|
||||||
|
Vector([3.0, 4.0, 5.0])
|
||||||
|
>>> v1 == v1_clone
|
||||||
|
True
|
||||||
|
|
||||||
|
|
||||||
|
Tests of sequence behavior::
|
||||||
|
|
||||||
|
>>> v1 = Vector([3, 4, 5])
|
||||||
|
>>> len(v1)
|
||||||
|
3
|
||||||
|
>>> v1[0], v1[len(v1)-1], v1[-1]
|
||||||
|
(3.0, 5.0, 5.0)
|
||||||
|
|
||||||
|
|
||||||
|
Test of slicing::
|
||||||
|
|
||||||
|
>>> v7 = Vector(range(7))
|
||||||
|
>>> v7[-1]
|
||||||
|
6.0
|
||||||
|
>>> v7[1:4]
|
||||||
|
Vector([1.0, 2.0, 3.0])
|
||||||
|
>>> v7[-1:]
|
||||||
|
Vector([6.0])
|
||||||
|
>>> v7[1,2]
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: Vector indices must be integers
|
||||||
|
|
||||||
|
|
||||||
|
Tests of dynamic attribute access::
|
||||||
|
|
||||||
|
>>> v7 = Vector(range(10))
|
||||||
|
>>> v7.x
|
||||||
|
0.0
|
||||||
|
>>> v7.y, v7.z, v7.t
|
||||||
|
(1.0, 2.0, 3.0)
|
||||||
|
|
||||||
|
Dynamic attribute lookup failures::
|
||||||
|
|
||||||
|
>>> v7.k
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
AttributeError: 'Vector' object has no attribute 'k'
|
||||||
|
>>> v3 = Vector(range(3))
|
||||||
|
>>> v3.t
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
AttributeError: 'Vector' object has no attribute 't'
|
||||||
|
>>> v3.spam
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
AttributeError: 'Vector' object has no attribute 'spam'
|
||||||
|
|
||||||
|
|
||||||
|
Tests of hashing::
|
||||||
|
|
||||||
|
>>> v1 = Vector([3, 4])
|
||||||
|
>>> v2 = Vector([3.1, 4.2])
|
||||||
|
>>> v3 = Vector([3, 4, 5])
|
||||||
|
>>> v6 = Vector(range(6))
|
||||||
|
>>> hash(v1), hash(v2), hash(v3), hash(v6)
|
||||||
|
(7, 384307168202284039, 2, 1)
|
||||||
|
>>> len(set([v1, v2, v3, v6]))
|
||||||
|
4
|
||||||
|
|
||||||
|
|
||||||
|
Tests of ``format()`` with Cartesian coordinates in 2D::
|
||||||
|
|
||||||
|
>>> v1 = Vector([3, 4])
|
||||||
|
>>> format(v1)
|
||||||
|
'(3.0, 4.0)'
|
||||||
|
>>> format(v1, '.2f')
|
||||||
|
'(3.00, 4.00)'
|
||||||
|
>>> format(v1, '.3e')
|
||||||
|
'(3.000e+00, 4.000e+00)'
|
||||||
|
|
||||||
|
|
||||||
|
Tests of ``format()`` with Cartesian coordinates in 3D and 7D::
|
||||||
|
|
||||||
|
>>> v3 = Vector([3, 4, 5])
|
||||||
|
>>> format(v3)
|
||||||
|
'(3.0, 4.0, 5.0)'
|
||||||
|
>>> format(Vector(range(7)))
|
||||||
|
'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0)'
|
||||||
|
|
||||||
|
|
||||||
|
Tests of ``format()`` with spherical coordinates in 2D, 3D and 4D::
|
||||||
|
|
||||||
|
>>> format(Vector([1, 1]), 'h') # doctest:+ELLIPSIS
|
||||||
|
'<1.414213..., 0.785398...>'
|
||||||
|
>>> format(Vector([1, 1]), '.3eh')
|
||||||
|
'<1.414e+00, 7.854e-01>'
|
||||||
|
>>> format(Vector([1, 1]), '0.5fh')
|
||||||
|
'<1.41421, 0.78540>'
|
||||||
|
>>> format(Vector([1, 1, 1]), 'h') # doctest:+ELLIPSIS
|
||||||
|
'<1.73205..., 0.95531..., 0.78539...>'
|
||||||
|
>>> format(Vector([2, 2, 2]), '.3eh')
|
||||||
|
'<3.464e+00, 9.553e-01, 7.854e-01>'
|
||||||
|
>>> format(Vector([0, 0, 0]), '0.5fh')
|
||||||
|
'<0.00000, 0.00000, 0.00000>'
|
||||||
|
>>> format(Vector([-1, -1, -1, -1]), 'h') # doctest:+ELLIPSIS
|
||||||
|
'<2.0, 2.09439..., 2.18627..., 3.92699...>'
|
||||||
|
>>> format(Vector([2, 2, 2, 2]), '.3eh')
|
||||||
|
'<4.000e+00, 1.047e+00, 9.553e-01, 7.854e-01>'
|
||||||
|
>>> format(Vector([0, 1, 0, 0]), '0.5fh')
|
||||||
|
'<1.00000, 1.57080, 0.00000, 0.00000>'
|
||||||
|
|
||||||
|
|
||||||
|
Tests of operator `==`::
|
||||||
|
|
||||||
|
>>> v1 = Vector(range(1, 4))
|
||||||
|
>>> v2 = Vector([1.0, 2.0, 3.0])
|
||||||
|
>>> v1 == v2
|
||||||
|
True
|
||||||
|
>>> from vector2d_v3 import Vector2d
|
||||||
|
>>> Vector([7, 8]) == Vector2d(7, 8)
|
||||||
|
True
|
||||||
|
>>> v1 == (1, 2, 3)
|
||||||
|
False
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from array import array
|
||||||
|
import reprlib
|
||||||
|
import math
|
||||||
|
import functools
|
||||||
|
import operator
|
||||||
|
import itertools
|
||||||
|
|
||||||
|
|
||||||
|
class Vector:
|
||||||
|
typecode = 'd'
|
||||||
|
|
||||||
|
def __init__(self, components):
|
||||||
|
self._components = array(self.typecode, components)
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return iter(self._components)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
components = reprlib.repr(self._components)
|
||||||
|
components = components[components.find('['):-1]
|
||||||
|
return 'Vector({})'.format(components)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return str(tuple(self))
|
||||||
|
|
||||||
|
def __bytes__(self):
|
||||||
|
return (bytes([ord(self.typecode)]) +
|
||||||
|
bytes(self._components))
|
||||||
|
|
||||||
|
# BEGIN VECTOR_V6_EQ
|
||||||
|
def __eq__(self, other):
|
||||||
|
if isinstance(other, Vector):
|
||||||
|
return (len(self) == len(other) and
|
||||||
|
all(a == b for a, b in zip(self, other)))
|
||||||
|
else:
|
||||||
|
return NotImplemented
|
||||||
|
# END VECTOR_V6_EQ
|
||||||
|
|
||||||
|
def __hash__(self):
|
||||||
|
hashes = (hash(x) for x in self)
|
||||||
|
return functools.reduce(operator.xor, hashes, 0)
|
||||||
|
|
||||||
|
def __abs__(self):
|
||||||
|
return math.sqrt(sum(x * x for x in self))
|
||||||
|
|
||||||
|
def __bool__(self):
|
||||||
|
return bool(abs(self))
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self._components)
|
||||||
|
|
||||||
|
def __getitem__(self, index):
|
||||||
|
cls = type(self)
|
||||||
|
if isinstance(index, slice):
|
||||||
|
return cls(self._components[index])
|
||||||
|
elif isinstance(index, int):
|
||||||
|
return self._components[index]
|
||||||
|
else:
|
||||||
|
msg = '{.__name__} indices must be integers'
|
||||||
|
raise TypeError(msg.format(cls))
|
||||||
|
|
||||||
|
shortcut_names = 'xyzt'
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
cls = type(self)
|
||||||
|
if len(name) == 1:
|
||||||
|
pos = cls.shortcut_names.find(name)
|
||||||
|
if 0 <= pos < len(self._components):
|
||||||
|
return self._components[pos]
|
||||||
|
msg = '{.__name__!r} object has no attribute {!r}'
|
||||||
|
raise AttributeError(msg.format(cls, name))
|
||||||
|
|
||||||
|
def angle(self, n):
|
||||||
|
r = math.sqrt(sum(x * x for x in self[n:]))
|
||||||
|
a = math.atan2(r, self[n-1])
|
||||||
|
if (n == len(self) - 1) and (self[-1] < 0):
|
||||||
|
return math.pi * 2 - a
|
||||||
|
else:
|
||||||
|
return a
|
||||||
|
|
||||||
|
def angles(self):
|
||||||
|
return (self.angle(n) for n in range(1, len(self)))
|
||||||
|
|
||||||
|
def __format__(self, fmt_spec=''):
|
||||||
|
if fmt_spec.endswith('h'): # hyperspherical coordinates
|
||||||
|
fmt_spec = fmt_spec[:-1]
|
||||||
|
coords = itertools.chain([abs(self)],
|
||||||
|
self.angles())
|
||||||
|
outer_fmt = '<{}>'
|
||||||
|
else:
|
||||||
|
coords = self
|
||||||
|
outer_fmt = '({})'
|
||||||
|
components = (format(c, fmt_spec) for c in coords)
|
||||||
|
return outer_fmt.format(', '.join(components))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def frombytes(cls, octets):
|
||||||
|
typecode = chr(octets[0])
|
||||||
|
memv = memoryview(octets[1:]).cast(typecode)
|
||||||
|
return cls(memv)
|
||||||
|
|
||||||
|
def __add__(self, other):
|
||||||
|
if len(self) != len(other):
|
||||||
|
cls_name = type(self).__name__
|
||||||
|
msg = 'cannot add {!r} of different dimensions'
|
||||||
|
raise ValueError(msg.format(cls_name))
|
||||||
|
return Vector(a + b for a, b in zip(self, other))
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user