1

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
JokerMartini
  • 5,674
  • 9
  • 83
  • 193
  • 1
    I think this question may be more suitable for [Code Review](http://codereview.stackexchange.com/), another Stack Exchange site. –  Mar 13 '14 at 23:12

4 Answers4

5

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).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
4

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.

Ricardo Cárdenes
  • 9,004
  • 1
  • 21
  • 34
0

Try:

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

And change operators for substractions etc.

dmh126
  • 257
  • 5
  • 15
0

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.
Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125