Search code examples
pythonpython-class

can only concatenate list (not "Point") to list In adding and subtracting points in python


I am trying to perform the following task : For two points (𝑥1,𝑦1)+(𝑥2,𝑦2)=(𝑥1+𝑥2,𝑦1+𝑦2)

I have this code executed :

class Point(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return "Point({0}, {1})".format(self.x, self.y)
    
    def __add__(self, other):
        return [self.x + other.x, self.y + other.y]
    def __sub__(self, other):
        return [self.x - other.x, self.y - other.y]

when I try to run the following piece of code, it says:

from functools import reduce
def add_sub_results(points):
    points = [Point(*point) for point in points]
    return [str(reduce(lambda x, y: x + y, points)), 
            str(reduce(lambda x, y: x - y, points))]

it returns

 return [str(reduce(lambda x, y: x + y, points)), 
      5             str(reduce(lambda x, y: x - y, points))]
      6 

TypeError: can only concatenate list (not "Point") to list

how can I solve this?


Solution

  • I think your __add__() and __sub__() methods of your Point class should be:

    class Point(object):
        ...
        
        def __add__(self, other):
            return Point(self.x + other.x, self.y + other.y) #<-- MODIFIED THIS
    
        def __sub__(self, other):
            return Point(self.x - other.x, self.y - other.y) #<-- MODIFIED THIS