Vectors that behave like numbers

Make a class work with +, ==, len and print.

What to build

A Vector class with four special methods.

Requirements

  • __add__ returns a new Vector of the sums of the matching items.
  • __eq__ is true when the two vectors hold the same values.
  • __len__ gives the number of values.
  • __str__ gives the form <1, 2, 3>.

Input

Two lines of whole numbers, with the same number of values on each.

Output

Three lines: the sum, equal True or equal False, then size N.

Constraints

Each line has from 1 to 100 numbers.

Example

Input:

1 2 3
4 5 6

Output:

<5, 7, 9>
equal False
size 3

Why it works

Each operator asks the object what it means, so the main program reads like simple arithmetic, while the details stay inside the class.

Examples

Example 1 · Input
1 2 3
4 5 6
Expected output
<5, 7, 9>
equal False
size 3
Example 2 · Input
1 2
1 2
Expected output
<2, 4>
equal True
size 2

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Store the numbers as a list in self.values.

Hint 2

__add__ returns a new Vector, built with zip.

Hint 3

__eq__ compares the two lists. __str__ joins the values with ", ".

Solution

Show one correct solution (try it yourself first)
class Vector:
    def __init__(self, values):
        self.values = values

    def __add__(self, other):
        return Vector([x + y for x, y in zip(self.values, other.values)])

    def __eq__(self, other):
        return self.values == other.values

    def __len__(self):
        return len(self.values)

    def __str__(self):
        return "<" + ", ".join(str(x) for x in self.values) + ">"

a = Vector([int(x) for x in input().split()])
b = Vector([int(x) for x in input().split()])
print(a + b)
print("equal", a == b)
print("size", len(a))

Lesson: Special methods →