Question

I've got 3 math operation functions I need to use on a point3 value. I was wondering if someone could shed any light on a way to better write these functions in a more clean and condensed fashion please.

Thank you.

ptA = [10.0, 20.0, 30]
ptB = [50, 50 ,50]
percent = .50


def addPoint3(ptA,ptB):

    idA = ptA[0] + ptB[0]
    idB = ptA[1] + ptB[1]
    idC = ptA[2] + ptB[2]

    return [idA,idB,idC]

def subtractPoint3(ptA,ptB):

    idA = ptA[0] - ptB[0]
    idB = ptA[1] - ptB[1]
    idC = ptA[2] - ptB[2]

    return [idA,idB,idC]

def percentagePoint3(ptA,percentage):

    idA = ptA[0] * percentage
    idB = ptA[1] * percentage
    idC = ptA[2] * percentage

    return [idA,idB,idC]



add = addPoint3(ptA,ptB)
sub = subtractPoint3(ptA,ptB)
per = percentagePoint3(ptA,percent)
print add,sub,per
Was it helpful?

Solution 2

You could write a Point class and implement the arithmetic operators. A naïve example would be:

class Point(object):
    def __init__(self, *args):
        self.coords = args

    def __add__(self, other):
        return Point(*[(x + y) for (x, y) in zip(self.coords, other.coords)])

    def __repr__(self):
        coord = ', '.join("{}".format(x) for x in self.coords)
        return "<Point ({})>".format(coord)

Which you could use like this:

ptA = Point(10.0, 20.0, 30)
ptB = Point(50, 50, 50)
>>> print ptA + ptB
<Point (60.0, 70.0, 80)>

You could expand it to use __sub__ and __mul__, and make it a bit more robust, because right now the implementation assumes many things:

  • That you always add points (this would break if you add an integer, for example)
  • That both points are the same dimension

All those things could be tested, to then generalize the methods.

OTHER TIPS

You can use zip and list comprehensions to simplify these. For example:

def addPoint3(ptA, ptB):
    return [a+b for a, b in zip(ptA, ptB)]

or

def percentagePoint3(ptA, percentage):
    return [pt * percentage for pt in ptA]

You might also consider implementing a class, rather than the lists, so you can define these as instance methods (for an example of this, see Ricardo Cárdenes' answer).

Try:

[ptA + ptB for ptA,ptB in zip(ptA, ptB)]

And change operators for substractions etc.

If speed is an issue then the fastest vectorized operations in python come not from lists but from numpy. Example:

import numpy as np

ptA = np.array([10.0,20.0,30])
ptB = np.ones(3)*50

pt3 = ptA + ptB #done with c/blas libraries under the hood.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top