python:How to use the correct data type?

115 Views Asked by At

I want to draw hundreds of 2D triangles(with labels) simultaneously in python+matplotlib, so I'm going to put these triangles in a list:

triangles =[ (label_1, A, B, C) , (label_2, D,E,F),...]

Here in (label , A, B, C), A,B,C be the three vertices of the triangle, so they are like pairs of real numbers like (x,y), and label might be a string(the color or the name of the triangle)

Now the question arise: how do I tell python that A=(x,y) is a point in the plane, not merely a "tuple of two elements" ? Since I need to do the operation "A+0.2*B", this results the error: "can't multiply sequence by non-int of type 'float'

Thanks in advance!

2

There are 2 best solutions below

4
On

You could create a custom Point class, and define behavior for addition and multiplication:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __mul__(self, value):
        return Point(self.x*value, self.y*value)
    def __rmul__(self, value):
        return self.__mul__(value)
    def __add__(self, other):
        return Point(self.x+other.x, self.y+other.y)
    def __repr__(self):
        return "Point({}, {})".format(self.x, self.y)

a = Point(1,2)
b = Point(23, 42)
x = a + 0.2 * b
print x
#result: Point(5.6, 10.4)
2
On

Why not use python's support for complex numbers? You can treat a complex number as a point in the plane (Argand plane).

To demonstrate complex number multiplication:

>>> (3+4j) + 0.2*(5+7j) #Use "j" instead of "i" in python
(4+5.4j)

BTW, your triangles might look like:

triangles = [
     ("label1", 3+4j, 5+6j, 7+8j),
     ("label2", 1+2j, 2+3j, 4+5j),
     #...
]