-2

I have written the following code to find the area of triangle in terms of its three sides a, b and c:

s = lambda a, b, c : (a + b + c)/2
area_tri = lambda a, b, c : (s(a,b,c) * (s(a,b,c)-a) * (s(a,b,c)-b) * \
   (s(a,b,c)-c)) ** 0.5
area_tri(1, 2, 3)

Output: 7.3484692283495345

I have two questions. First, how to reduce the repeated typing of s(a,b,c) in the lambda function for area_tri? Secondly, conjoined to the first question, how to reduce the number of invocations to lambda s in area_tri?

Seshadri R
  • 1,192
  • 14
  • 24
  • 5
    Just do not write these functions as lambdas – awesoon Aug 11 '18 at 08:01
  • ¿¿¿ `s(a,b,c)*c` ??? isn't it `s(a,b,c)-c` ??? – gboffi Aug 11 '18 at 08:34
  • Thanks for pointing out the error. My apologies. I edited my question to reflect your correction. – Seshadri R Aug 11 '18 at 13:39
  • I am not able to understand the philosophy or rationale behind upvoting and downvoting. Simple and naive questions like how to find number of elements in a list (https://stackoverflow.com/questions/1712227/how-to-get-the-number-of-elements-in-a-list-in-python)- for which the answer is straight forward and can be gotten within a minute of consulting python tutorial - get 1540 points. But, I have asked something on using python lambda with my own program. And, it gets -2 (till the time of writing this comment). – Seshadri R Aug 12 '18 at 05:45

1 Answers1

1

There is a way:

area_tri = lambda a, b, c: (lambda x=s(a,b,c): (x * (x-a) * (x-b) * (x*c)) ** 0.5)()

Without a lambda but in one line it can be a bit shorter:

def area_tri(a, b, c): x = s(a,b,c); return (x * (x-a) * (x-b) * (x*c)) ** 0.5

However unless you're golfing, this should be properly formatted:

def area_tri(a, b, c):
    x = s(a,b,c)
    return (x * (x-a) * (x-b) * (x*c)) ** 0.5
Anonymous
  • 11,740
  • 3
  • 40
  • 50