0

I ran the following code in Python 2.7 and got an error. Why?

CODE:

def triangle_area(a, b, c):
    """
    Returns the area of a triangle given the length of three sides
    Code source: [here][1]
    """
    def distance(p1, p2):
        return math.hypot(p1[0]-p2[0], p1[1]-p2[1])

    side_a = distance(a, b)
    side_b = distance(b, c)
    side_c = distance(c, a)
    s = 0.5 * ( side_a + side_b + side_c)
    return math.sqrt(s * (s - side_a) * (s - side_b) * (s - side_c))

Running the following: y = triangle_area(10.1,1.1,11.2)

Produces this error: Traceback (most recent call last):

[snip]
....in distance
return math.hypot(p1[0]-p2[0], p1[1]-p2[1])
TypeError: 'float' object has no attribute '__getitem__'
5
  • P1 or P2 is float objects.It has no indexing. Commented Aug 27, 2015 at 21:10
  • 2
    You're sending floating-point numbers to the distance function, which then tries to index them. You can't do that. What are you expecting it to do? Commented Aug 27, 2015 at 21:10
  • I think you have nailed it. I found this code at code.activestate.com/recipes/576896-3-point-area-finder and, wrongly, assumed it worked. Off to recode... Commented Aug 27, 2015 at 21:13
  • Found code looks delicious, but you never know. Commented Aug 27, 2015 at 21:14
  • Agreed! I think the found code was intended to pass three points (x,y) rather than the scalars I am sending. I'll work up the solution and post it as an answer. Your comments helped me discover the problem. TNX Commented Aug 27, 2015 at 21:22

1 Answer 1

1

The distance function in this snippet is assuming that you will pass it tuples for the (x,y) position of the points.

So to compute the area of a triangle with vertices at (0,0), (0,1), (1,1) you would call

triangle_area((0,0), (0,1), (1,1))
Sign up to request clarification or add additional context in comments.

1 Comment

Yup! I discovered that I was thinking the function handled the length of sides. WRONG! It, as you noted, handles the position of three points. TNX for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.