0

My function is made to get the area of any arbitrary triangle.

Here is the way that I know works

def areaOfTriangle(vertices):
    x1 = vertices[0][0]
    y1 = vertices[0][1]
    x2 = vertices[1][0]
    y2 = vertices[1][1]
    x3 = vertices[2][0]
    y3 = vertices[2][1]
    area = (1.0/2.0)*(x2*y3 - x3*y2 - x1*y3 + x3*y1 + x1*y2 - x2*y1)
    return area

However, I think this is crap so here's what I had as a sketched out thought,

def areaOfTriangle(vertices):
    coord1 = vertices[0]
    coord2 = vertices[1]
    coord3 = vertices[2]
    for x1,y1 in coord1:
        for x2, y2 in coord2:
            for x3, y3 in coord3:
                area = (1.0/2.0)*(x2*y3 - x3*y2 - x1*y3 + x3*y1 + x1*y2 - x2*y1)
    return area

However, this apparently doesn't play too nice with lists. I thought this would work in the way that once can get keys and values from dictionaries...but lists don't have the iteritems() method. Then I thought about converting the lists into dictionaries, but the keys are unique in dicts and hence they only pop up once....which would make my function not work properly.

4

1 回答 1

3

You use tuple unpacking:

(x1, y1), (x2, y2), (x3, y3) = vertices

Python can unpack nested sequences into separate variables, as long as you create the same nesting structure on the left-hand-side.

The looping will not work because you are trying to unpack 2-value tuples per loop iteration, where the iteration would only yield only 1 value.

This works across python versions.

Demonstration:

>>> vertices = [(1,2), (3, 4), (5, 6)]
>>> (x1, y1), (x2, y2), (x3, y3) = vertices
>>> print x1, y1, x2, y2, x3, y3
1 2 3 4 5 6
于 2013-03-30T14:02:18.303 回答