In PYTHON 3 Would like an alternative approach to this question. See answer belo
ID: 3598616 • Letter: I
Question
In PYTHON 3
Would like an alternative approach to this question. See answer below the question.
def morph(S, B):
'''
Input:
- S: a list of distinct Vecs
- B: a list of linearly independent Vecs all in Span S
Output: a list of pairs of vectors to inject and eject (see problem description)
Example:
>>> # This is how our morph works. Yours may yield different results.
>>> # Note: Make a copy of S to modify instead of modifying S itself.
>>> from vecutil import list2vec
>>> from vec import Vec
>>> S = [list2vec(v) for v in [[1,0,0],[0,1,0],[0,0,1]]]
>>> B = [list2vec(v) for v in [[1,1,0],[0,1,1],[1,0,1]]]
>>> D = {0, 1, 2}
>>> morph(S, B) == [(Vec(D,{0: 1, 1: 1, 2: 0}), Vec(D,{0: 1, 1: 0, 2: 0})), (Vec(D,{0: 0, 1: 1, 2: 1}), Vec(D,{0: 0, 1: 1, 2: 0})), (Vec(D,{0: 1, 1: 0, 2: 1}), Vec(D,{0: 0, 1: 0, 2: 1}))]
True
>>> S == [list2vec(v) for v in [[1,0,0],[0,1,0],[0,0,1]]]
True
>>> B == [list2vec(v) for v in [[1,1,0],[0,1,1],[1,0,1]]]
True
>>> from GF2 import one
>>> D = {0, 1, 2, 3, 4, 5, 6, 7}
>>> S = [Vec(D,{1: one, 2: one, 3: one, 4: one}), Vec(D,{1: one, 3: one}), Vec(D,{0: one, 1: one, 3: one, 5: one, 6: one}), Vec(D,{3: one, 4: one}), Vec(D,{3: one, 5: one, 6: one})]
>>> B = [Vec(D,{2: one, 4: one}), Vec(D,{0: one, 1: one, 2: one, 3: one, 4: one, 5: one, 6: one}), Vec(D,{0: one, 1: one, 2: one, 5: one, 6: one})]
>>> sol = morph(S, B)
>>> sol == [(B[0],S[0]), (B[1],S[2]), (B[2],S[3])] or sol == [(B[0],S[1]), (B[1],S[2]), (B[2],S[3])]
True
>>> # Should work the same regardless of order of S
>>> from random import random
>>> sol = morph(sorted(S, key=lambda x:random()), B)
>>> sol == [(B[0],S[0]), (B[1],S[2]), (B[2],S[3])] or sol == [(B[0],S[1]), (B[1],S[2]), (B[2],S[3])]
True
'''
result = list()
A = set()
for z in B:
result.append((z,exchange(S,A,z)))
S.remove(exchange(S,A,z))
S.append(z)
return result
Explanation / Answer
class Vector(tuple): '''"Class to calculate the usual operations with vectors in bi and tridimensional coordinates. Too with n-dimmensinal.''' # __slots__=('V') #It's not possible because V is a variable list of param. def __new__(cls, *V): '''The new method, we initialize the coordinates of a vector. You can initialize a vector for example: V = Vector() or V = Vector(a,b) or V = Vector(v1, v2, ..., vn)''' if not V: V = (0, 0) elif len(V) == 1: raise ValueError('A vector must have at least 2 coordinates.') return tuple.__new__(cls, V) def __add__(self, V): '''The operator sum overloaded. You can add vectors writing V + W, where V and W are two vectors.''' if len(self) != len(V): raise IndexError('Vectors must have same dimmensions.') else: added = tuple(a + b for a, b in zip(self, V)) return Vector(*added) __radd__ = __add__ def __sub__(self, V):
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.