Как напечатать объект линейной системы в виде строки в Python? Ошибка типа: объект «Вектор» не повторяется - PullRequest
0 голосов
/ 02 мая 2020

У меня была похожая проблема при работе с векторами и плоскостями, но я нашел здесь решение: добавьте '.coordinates' к векторным объектам во всех блоках с ошибкой. С этим он не работает, и я исчерпал каждый трюк, который знал, пытаясь это исправить. Вот начальный блок кода, который был задан в классе для печати:

def __str__(self):
        ret = 'Linear System:\n'
        temp = ['Equation {}: {}'.format(i+1,p) for i,p in enumerate((self.planes))]
        ret += '\n'.join(temp)
        return ret

И есть материал для печати:

p0 = Plane(normal_vector=Vector(['1','1','1']), constant_term='1')
p1 = Plane(normal_vector=Vector(['0','1','0']), constant_term='2')
p2 = Plane(normal_vector=Vector(['1','1','-1']), constant_term='3')
p3 = Plane(normal_vector=Vector(['1','0','-2']), constant_term='2')

s = LinearSystem([p0,p1,p2,p3])


print "{},{},{},{}".format(s[0],s[1],s[2],s[3])

Также, на всякий случай, вот Классы Vector, Plane и LinearSystem, возможно, проблема где-то здесь:

class Vector (объект):

CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'Cannot compute an angle with the zero vector'

def __init__(self, coordinates):
    try:
        if not coordinates:
            raise ValueError
        self.coordinates = tuple(Decimal(x) for x in coordinates)
        self.dimension = len(self.coordinates)

    except ValueError:
        raise ValueError('The coordinates must be nonempty')

    except TypeError:
        raise TypeError('The coordinates must be an iterable')

class Plane (объект):

NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'

def __init__(self, normal_vector=None, constant_term=None):
    self.dimension = 3

    if not normal_vector:
        all_zeros = ['0']*self.dimension
        normal_vector = Vector(all_zeros)
    self.normal_vector = normal_vector

    if not constant_term:
        constant_term = Decimal('0')
    self.constant_term = Decimal(constant_term)

    self.set_basepoint()


def set_basepoint(self):
    try:
        n = self.normal_vector
        c = self.constant_term
        basepoint_coords = ['0']*self.dimension

        initial_index = Plane.first_nonzero_index(n.coordinates)
        initial_coefficient = n.coordinates[initial_index]

        basepoint_coords[initial_index] = c/initial_coefficient
        self.basepoint = Vector(basepoint_coords)

    except Exception as e:
        if str(e) == Plane.NO_NONZERO_ELTS_FOUND_MSG:
            self.basepoint = None
        else:
            raise e

class LinearSystem (object):

ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG = 'All planes in the system should live in the same dimension'
NO_SOLUTIONS_MSG = 'No solutions'
INF_SOLUTIONS_MSG = 'Infinitely many solutions'

def __init__(self, planes):
    try:
        d = planes[0].dimension
        for p in planes:
            assert p.dimension == d

        self.planes = planes
        self.dimension = d

    except AssertionError:
        raise Exception(self.ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG)

Кстати, normal_vector () и normalized () здесь делают одно и то же:

> def magnitude(self):
>         coordinates_squared = [x**2 for x in self.coordinates]
>         return sum(coordinates_squared) ** Decimal('0.5')
>     def normalized(self):
>         try:
>             magnitude = self.magnitude()
>             return self.times_scalar(Decimal('1.0')/magnitude)
>         except ZeroDivisionError:
>             raise Exception(self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG)

Я также получал ту же ошибку «Вектор не повторяем» в этом блоке, но исправил ее с помощью этого «pn.coordinates» (умное право:))

def indices_of_first_nonzero_terms_in_each_row(self):
    num_equations = len(self)
    num_variables = self.dimension

    indices = [-1] * num_equations

    for i,p in enumerate(self.planes):
        try:
            pn = p.normal_vector

            indices[i] = p.first_nonzero_index(pn.coordinates)
        except Exception as e:
            if str(e) == Plane.NO_NONZERO_ELTS_FOUND_MSG:
                continue
            else:
                raise e

Как вы думаете, у меня могут быть эти проблемы, потому что я использую Python 2,7, а не 3? Спасибо, что читаете и пытаетесь помочь!

...